使用 dplyr 匹配两个日期字段

Matching two date fields using dplyr

所以我有一个这样的数据框:

ID   key  date1
001   02  2018-02-16
001   02  2018-02-19
001   03  2018-02-17
001   03  2018-02-22
001   04  2017-01-01
002   11  2019-12-21
002   12  2019-12-21
002   13  2019-12-22

还有另一个数据框 (DF2)

ID   key  date2
001   02  2018-02-20
001   03  2018-03-22
002   13  2019-12-22
002   13  2019-12-21

所以这个任务在概念上很简单:

我想找到 DF1 中存在的前一个日期到 DF2 中的每个日期。

这是什么意思?例如在 DF2 中,我们看到 2018-02-20 的日期以及相应的 Key 和 ID。所以我去 DF1 找到匹配的 ID 和 Key,这给了我两种可能性。我需要的是前一个,而不是后一个。因此它将是 2018-02-19。我最终会计算天数。

最终的 df 应该是这样的:

ID   key  date2           date1   day_diff
001   02  2018-02-20 2018-02-19          1
001   03  2018-03-22 2018-02-22         28
002   13  2019-12-22 2019-12-22          0
002   13  2019-12-21         NA         NA

同样,我们只需要 DF2 每一行中的日期之前的日期。如果没有以前的日期,这也需要 return NA。

这个有用吗:

library(dplyr)
df1 %>% group_by(ID, key) %>% filter(date1 == max(date1)) %>% 
fuzzyjoin::fuzzy_right_join(df2, by = c('ID' = 'ID', 'key' = 'key', 'date1' = 'date2'), match_fun = list(`==`, `==`, `<=`)) %>% 
ungroup() %>% select('ID' = ID.y, 'key' = key.y, date2, date1) %>% mutate(day_diff = as.numeric(date2 - date1))
# A tibble: 4 x 5
  ID    key   date2      date1      day_diff
  <chr> <chr> <date>     <date>        <dbl>
1 001   02    2018-02-20 2018-02-19        1
2 001   03    2018-03-22 2018-02-22       28
3 002   13    2019-12-22 2019-12-22        0
4 002   13    2019-12-21 NA               NA