有以下数据框:
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)
Run Code Online (Sandbox Code Playgroud)
我需要找到df1
其中也存在的ID df2
并将其所有信息导出到新的数据框(比方说df3
).在此基础上df3
应该如下:
id1 spent
1 10
3 30
4 40
Run Code Online (Sandbox Code Playgroud)
如果你能解决这个问题我会很感激.
使用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
Run Code Online (Sandbox Code Playgroud)
您可以使用该data.table
包,merge
如果您要合并大量ID ,则可能比使用包更快.例如,
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
Run Code Online (Sandbox Code Playgroud)
nb unique
也可能没有必要,但我把它包括在内,以防真实数据包含重复的id2
s.
编辑这J()
是必要的,另见Matthew Dowle的评论.