user2014 user2014 - 3 months ago 6
R Question

How to combine two data frames where only one column is same in two data frames in R

DF1 is

No ID
2 5678
3 3241
5 8167


DF2 is

NO Name meaning
1 a aaple
2 b bat
3 c cat
4 d dam
5 e egg


I want to combine DF1 AND DF2 to DF3(this contains all the columns from DF1 and DF2)

expected ouput DF3 is

No Name meaning ID
1 a aaple
2 b bat 5678
3 c cat 3241
4 d dam
5 e egg 8167


I tried using cbind, but R is giving an error 'Process failed. Script terminated abnormally'

Then i used 'merge' function, but the result is

No Name meaning ID
2 b bat 5678
3 c cat 3241
5 e egg 8167


Please let me know if i am wrong in using functions

Answer

You need to specify all parameter to be TRUE if you want to keep all records. Have a look at ?merge, by default, all, all.x and all.y are set to be FALSE and it is an inner join:

merge(df1, df2, by = "No", all = T)

#   No   ID Name meaning
# 1  1   NA    a   aaple
# 2  2 5678    b     bat
# 3  3 3241    c     cat
# 4  4   NA    d     dam
# 5  5 8167    e     egg
Comments