我有两个数据帧,一个包含日期列表(df1
),另一个包含ID的日期范围(df2
).如果df1
中的日期位于df2
中的日期范围内,我想在df2
中添加一列.
## This is my base data
df1 <-
structure(list(Date = structure(c(18848, 18848, 18849, 18890,
18892, 18901, 18904, 18904, 18906, 18906, 18907, 18911, 18911,
18922, 18923, 18925, 18926, 18927, 18929), class = "Date"), Id = c(4,
6, 4, 6, 4, 4, 4, 6, 4, 6, 4, 4, 6, 4, 4, 4, 4, 6, 6)), row.names = c(NA,
19L), class = "data.frame")
## This is my date range table
df2 <- structure(list(Date.Start = structure(c(18898, 18897, 18848,
18898, 18897), class = "Date"), Date.End = structure(c(18924,
18924, 18903, 18924, 18924), class = "Date"), Id = c(6, 6, 4,
4, 4), Return.Value = c(1, 2, 3, 4, 5)), row.names = c(NA, 5L
), class = "data.frame")
因此,对于第一行df1
,Date=‘2021-08-09’位于日期范围‘2021-08-09’到‘2021-10-03’(第3行,共df2
行)内,因此我想将Return Value
列添加到df1
,值为3
.
我的预期输出是:
我try 了这个链接Check if a date is in range of lookup table,但我想从df2
中添加一列,而不是返回逻辑向量.