如何基于两列组合两个数据帧?

时间:2011-07-15 15:07:54

标签: r merge dataframe

我知道我可以使用plyr及其朋友来组合数据框,也可以使用merge,但到目前为止我还不知道如何根据2列合并两个数据帧和多列?

3 个答案:

答案 0 :(得分:120)

请参阅?merge上的文档,其中说明:

By default the data frames are merged on the columns with names they both have, 
 but separate specifications of the columns can be given by by.x and by.y.

这显然意味着merge将基于多个列合并数据帧。从文档中给出的最后一个例子:

x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match

此示例旨在演示incomparables的使用,但它也说明了使用多列进行合并。您还可以使用xyby.xby.y中指定单独的列。

答案 1 :(得分:45)

希望这会有所帮助;

df1 = data.frame(CustomerId=c(1:10),
             Hobby = c(rep("sing", 4), rep("pingpong", 3), rep("hiking", 3)),
             Product=c(rep("Toaster",3),rep("Phone", 2), rep("Radio",3), rep("Stereo", 2)))

df2 = data.frame(CustomerId=c(2,4,6, 8, 10),State=c(rep("Alabama",2),rep("Ohio",1),   rep("Cal", 2)),
             like=c("sing", 'hiking', "pingpong", 'hiking', "sing"))

df3 = merge(df1, df2, by.x=c("CustomerId", "Hobby"), by.y=c("CustomerId", "like"))

假设df1$Hobbydf2$like意思相同。

答案 2 :(得分:2)

您还可以使用加入命令(dplyr)。

例如:

new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))
相关问题