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.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s