[英]find the common ids between two data frames in R
有以下数据框:
id1<-c(1,2,3,4,5)
spent<-c(10,20,30,40,50)
id2<-c(1,3,4)
x<-c(1,2,2)
df1<-data.frame(id1,spent)
df2<-data.frame(id2,x)
我需要找到df1
中的id,它们也存在于df2
并将所有信息导出到一个新的数据帧(比方说df3
)。 在此基础上, df3
应如下所示:
id1 spent
1 10
3 30
4 40
如果你能解决这个问题我会很感激。
使用merge
see ?merge
获取有关by.x
和by.y
参数的信息
merge(df1, df2, by.x="id1", by.y="id2")[,-3] # this is the desired output you showed
id1 spent
1 1 10
2 3 30
3 4 40
merge(df1, df2, by.x="id1", by.y="id2") # this is with "all their information"
id1 spent x
1 1 10 1
2 3 30 2
3 4 40 2
你可以使用data.table
包,如果你要合并很多ID,这可能比使用merge
更快。 例如,
library(data.table)
dt1 <- data.table(id1, spent, key = "id1")
dt1[J(unique(df2$id2))]
# id1 spent
# 1: 1 10
# 2: 3 30
# 3: 4 40
nb unique
也可能没有必要,但我包含它以防真实数据包括重复的id2
s。
编辑 J()
是必要的,另外请参阅Matthew Dowle的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.