基于同一ID列从两个数据帧中提取值

时间:2019-10-05 18:10:47

标签: r

我想从两个不同数据框中的值创建数据名人 列ID中包含相同的值

输入数据

df1<- data.frame(ID = c(102, 205, 333, 434, 512), Order1 = c("ball", 
"ball", "pen", "glass", "scale"))
df2 <- data.frame(ID = c(102, 205, 333, 434, 512), ActOrder1 = c("cap", 
"watch", "cup", "pen", "pencil"), ActOrder2 = c("cap", "fan", "phone", 
"NA",  "NA"))

对于df1的Order1列中ball的所有值,我想从df2中提取ActOrder1和Actorder2列中的值

输出

df3 <- data.frame(ID = c(102, 205), Order1 = c("ball", "ball"), 
ActOrder1 = c("cap", "watch"), ActOrder2 = c("cap", "fan") )

1 个答案:

答案 0 :(得分:1)

我们可以将left_joinfilter一起使用

library(dplyr)
left_join(df1, df2, by = 'ID') %>%
   filter(Order1 == 'ball')  %>%
   select(names(df1), starts_with('ActOrder'))