R 添加列以匹配另一个数据框

R add column to match another dataframe

我想向主 table x 添加列以将其列与数据帧 y 相匹配。有什么好的解决方案可以推荐吗?

x=data.frame(a=1:3, b=1:3)
y=data.frame(c=NA,b=NA, a=NA)

我希望 x 为 x=data.frame(c=NA, b=1:3, a=1:3),以便 x table 具有与 y 相同顺序的相同列。

非常感谢!

您可以merge然后重新排列列

merge(x, y, by = c("a", "b"), all.x = TRUE)[names(y)]
#   c b a
#1 NA 1 1
#2 NA 2 2
#3 NA 3 3