Joining 2 R data sets with different column names

December 22, 2012
By

(This article was first published on minimalR.com » r-bloggers, and kindly contributed to R-bloggers)

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.

To leave a comment for the author, please follow the link and comment on his blog: minimalR.com » r-bloggers.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.