Joining 2 R data sets with different column names

Joining or merging two data sets is one of the most common tasks in preparing and analysing data. In fact a Google search returns 253 million results.

However most examples assume that the columns that you want to merge by have the same names in both data sets which is often not the case. For example:

 

  mergedData <- merge(a, b, by “ID”)

 

Often you have data sets from different sources that do not have  the same naming convention. While it’s straight forward to merge using differently named columns, most Googled examples either don’t cover it explicitly or suggest that you rename your column names to be the same !

Merge using the by.x and by.y arguments to specify the names of the columns to join by.

 

  mergedData <- merge(a, b, by.x=c(“colNameA”),
    
by.y=c(“colNameB”))

 

where colNameA and colNameB are the column names in a and b to merge on.