2016-06-30 74 views
1

我有兩個數據幀合併2數據幀:2列比

df1=data.frame(w=c(10,'a','a',14,''),data='other stuff') 
df2=data.frame(c=10:14,n=letters[1:5],data='stuff') 
> df1;df2 
    w  data 
1 10 other stuff 
2 a other stuff 
3 a other stuff 
4 14 other stuff 
5 other stuff 
    c n data 
1 10 a stuff 
2 11 b stuff 
3 12 c stuff 
4 13 d stuff 
5 14 e stuff 

我想使最終的DF,看起來像(手工製作):

10 stuff other stuff 
a  stuff other stuff 
a  stuff other stuff 
14 stfff other stuff 
     stuff other stuff 

我試圖

merge(df1,df2,by.x='w',by.y='c|n') 

無濟於事,我不知道如何解決這個問題。需要注意的是DF1和DF2是1000×48尺寸

+0

你想最終數據框的列名什麼是?您似乎在每個單獨的數據框中都有一個具有相同名稱的列。 –

+0

匹配來自列w,且值不一致。一些值是數字,另一些是字符。我希望能夠一次性合併所有的數據 – alex

+0

您可以將數據列中的值更改爲1,2,3,...等,這樣我們就可以瞭解預期的輸出。 – zx8754

回答

3

我們可以將DF2使一個鍵列,以配合DF1然後使用合併:

#dummy data updated data columns 
df1 = data.frame(w = c(10,'a','a',14,''), data = paste('otherStuff', 1:5)) 
df2 = data.frame(c = 10:14, n = letters[1:5], data = paste('stuff', 1:5)) 

df1;df2 

# w   data 
# 1 10 otherStuff 1 
# 2 a otherStuff 2 
# 3 a otherStuff 3 
# 4 14 otherStuff 4 
# 5 otherStuff 5 

# c n data 
# 1 10 a stuff 1 
# 2 11 b stuff 2 
# 3 12 c stuff 3 
# 4 13 d stuff 4 
# 5 14 e stuff 5 


library(dplyr) 
library(tidyr) 

merge(df1, 
     gather(df2, key = "Group", value = "w", -data), 
     by = "w", all.x = TRUE) 


# w  data.x data.y Group 
# 1 otherStuff 5 <NA> <NA> 
# 2 10 otherStuff 1 stuff 1  c 
# 3 14 otherStuff 4 stuff 5  c 
# 4 a otherStuff 2 stuff 1  n 
# 5 a otherStuff 3 stuff 1  n