How do I combine two data-frames based on two columns?

Sam picture Sam · Jul 15, 2011 · Viewed 290.4k times · Source

I know I can use the plyr and its friends to combine dataframes, and merge as well, but so far I don't know how to merge two dataframes with multiple columns based on 2 columns?

Answer

joran picture joran · Jul 15, 2011

See the documentation on ?merge, which states:

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.

This clearly implies that merge will merge data frames based on more than one column. From the final example given in the documentation:

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

This example was meant to demonstrate the use of incomparables, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x and y using by.x and by.y.