-3

I have two data set as below df1 :

ID   name 
1   
1   
2   
2   
3   
3   
3   

df2 :

ID   var1 name 
1     54   aaa
1     12   aaa
2     55   bbb
2     87   bbb
3     1    ccc
3     2    ccc
3     12   ccc
3     14   ccc   
3     16   ccc   
...

I want to fill the nave variable in the df1 data by using df2. How should I do that?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Boram Lim
  • 313
  • 3
  • 15
  • It has been asked http://stackoverflow.com/questions/1299871/how-to-join-data-frames-in-r-inner-outer-left-right – dimitris_ps Apr 19 '15 at 00:33
  • if there are "ID"s that exist only df2 data and I want to merge data sets by only using commonly existed "ID"? – Boram Lim Apr 19 '15 at 01:47

1 Answers1

1

Below is a quick trial.

df1 <- data.frame(ID = c(1,2,3))
df2 <- data.frame(ID = c(1,2,2), name=c('aaa','bbb','bbb'))
# get unique ID and name pairs
df2 <- unique(df2)

# merge that keep all x rows (or left outer join by df1)
merge(df1, df2, by="ID", all=TRUE)
  ID name
1  1  aaa
2  2  bbb
3  3 <NA>

## Update
df1 <- data.frame(ID = c(1,1,2,2,3,3,3))

names <- data.frame(ID = c(1,2,3), names=c('aaa','bbb','ccc'))
df2 <- merge(data.frame(ID = c(1,1,2,2,3,3,3,3)), names, by="ID") 
df2 <- unique(df2)

merge(df1, df2, by="ID", all.x = TRUE)
Jaehyeon Kim
  • 1,328
  • 11
  • 16