这是一个完全在dplyr 中的解决方案。我假设 id 和 date 代表唯一键。
让我们添加一些数据以实现可重复性
set.seed(23489)
n <- 10
df1 <- data.frame(
id=sample(1e4:9e4, n),
date=sample(seq(as.Date('2015/01/01'), as.Date('2017/01/01'), by="day"), n),
vegetables= c("Broccoli", "Cabbage", "Calabrese", "Carrots", "Cauliflower",
"Celery", "Chard", "Endive", "Fiddleheads", "Frisee"),
fruits=c("Jabuticaba", "Jackfruit", "Jambul", "Jujube", "Juniper berry",
"Kiwi", "Kumquat", "Lemon", "Lime", "Loquat"),
metric=rnorm(n=n)
)
df2 <- df1[sample(seq_len(nrow(df1)), n/2), ]
接下来,我们生成您想要的输出
df1 %>%
left_join(select(mutate(df2, InDF2=TRUE), id, date, InDF2), by=c("id", "date")) %>%
mutate(InDF2=ifelse(is.na(InDF2), FALSE, TRUE))
# id date vegetables fruits metric InDF2
# 1 80283 2016-11-26 Broccoli Jabuticaba 1.68765979 FALSE
# 2 14766 2016-10-18 Cabbage Jackfruit -0.16774908 FALSE
# 3 19532 2015-03-29 Calabrese Jambul -1.18328968 TRUE
# 4 46187 2015-03-09 Carrots Jujube 1.83044569 FALSE
# 5 76852 2016-01-11 Cauliflower Juniper berry -0.05744373 FALSE
# 6 45507 2015-10-27 Celery Kiwi -1.78166251 FALSE
# 7 65227 2016-07-07 Chard Kumquat -1.84756162 TRUE
# 8 71433 2015-05-25 Endive Lemon 0.77346596 TRUE
# 9 17002 2016-10-22 Fiddleheads Lime 1.09118108 TRUE
# 10 52797 2015-06-29 Frisee Loquat -0.46491328 TRUE