合并两个数据框,仅保留匹配的列

时间:2019-05-20 14:03:33

标签: r

(EDIT)我有两个带有不同列的数据框。我想将它们串联起来,只保留我想要的列。

#this is the data
df1 = data.frame(Id = c(129,109), Product = c('nutella', 'crepes'), 
             sales= c(1000000, 200000), ratings = c(5,3), Company=c('a','b'))
df2 = data.frame(Id = c(154,198), Product = c('cheesecake', 'oreo'), 
             sales= c(150000, 3000000), Taxpaid = c(120, 3000), 
             Company=c('c','d'))


#Desired Output:

    Id     Product       
    129    nutella     
    109    crepes      
    154    cheesecake  
    198    oreo        

1 个答案:

答案 0 :(得分:1)

我们可以对两个数据集的列intersectrbind数据集进行

nm1 <- intersect(names(df1), names(df2))
rbind(df1[nm1], df2[nm1])