如何减去两个长度不等的数据帧

时间:2014-05-21 11:53:53

标签: r dataframe

x<-c(1:5)
y<-c("a","b","c","d","e")
df1<- as.data.frame(cbind(x,y))

x<-c(1:10)
y<-c("a","b","c","d","e","f","g","h","i","j")
df2<- as.data.frame(cbind(x,y))

我可以使用

设置这些数据框之间的差异
setdiffDF(df1, df2) 

我想要做的是将这个结果从df2中拿走,这样我就可以完全匹配df1和df2了

谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用intersect中的dplyr(不要与base::intersect混淆)。

> library(dplyr)
> intersect(df1, df2)
##   x y
## 1 1 a
## 2 2 b
## 3 3 c
## 4 4 d
## 5 5 e

答案 1 :(得分:1)

你也可以使用基础R merge功能

merge(df1, df2, by = "y")

或者您可以同时合并yx

merge(df1, df2, by = c("y", "x"))

如果您希望将所有值保留在df1中,无论它们是否与df2匹配,您都可以

merge(df1, df2, by = c("y", "x"), all.x = TRUE)