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

我知道我可以使用plyr和它的朋友来合并dataframe,并merge ,但到目前为止,我不知道如何合并两列数据框与多列基于2列?

请参阅“ ?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将合并基于多个列的dataframe。 从文档中给出的最后一个例子:

 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的使用,但它也演示了使用多个列进行合并。 您也可以使用by.xby.yxy每一个中指定单独的列。

希望这可以帮助;

 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是一样的东西。