我想从两个不同数据框中的值创建数据名人 列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") )
答案 0 :(得分:1)
我们可以将left_join
与filter
一起使用
library(dplyr)
left_join(df1, df2, by = 'ID') %>%
filter(Order1 == 'ball') %>%
select(names(df1), starts_with('ActOrder'))