Few more things about merging in R


R Tutorial 5.1


In the last article "A to Z about Merging in R", I had tried to cover almost everything about merging in R. Few things, I believe I have missed, are being covered in this article.

So have fun !

Complication A:


In the previous article we had addressed only to the situations where there were only 1 matching keys; What if the matching keys are more than 1.  Let's see how to merge in this case.

#Let's prepare two dataset:

Data_1 = data.frame(year = c( rep(2010,3),rep(2011,3))  , month = seq(1:6), rainfall = c(111,123,134,145,170,184) )
Data_2 = data.frame(year = c( rep(2010,3),rep(2011,3))  , month = seq(1:6), Temp_celcius = c(23,20,21,18,14,19) )

Now the matching key here is year + month

Data_merged= merge(Data_1, Data_2, by = c("year","month" ))

Please run and see the results.

Complication B:


The name of matching key(s) is/are not same across datasets.

# As a matter of best practice, first we clear the workspace
rm(list = ls())

#Let's prepare two dataset, this time in second dataset, one of the matching keys has been given a different name

Data_1 = data.frame(year = c( rep(2010,3),rep(2011,3))  , month = seq(1:6), rainfall = c(111,123,134,145,170,184) )
Data_2 = data.frame(year = c( rep(2010,3),rep(2011,3))  , mon_id = seq(1:6), Temp_celcius = c(23,20,21,18,14,19) )


Data_merged= merge(x= Data_1, y= Data_2, by.x = c("year","month" ), by.y = c("year","mon_id" ))


Please run and see the results.


Enjoy reading our other articles and stay tuned with us.

Kindly do provide your feedback in the 'Comments' Section and share as much as possible.

No comments:

Post a Comment

Do provide us your feedback, it would help us serve your better.