【问题标题】:Matching two date fields using dplyr使用 dplyr 匹配两个日期字段
【发布时间】:2020-11-30 17:25:42
【问题描述】:

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

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 以及相应的密钥和 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 每一行中的日期之前的日期。如果没有以前的日期,这也需要返回 NA。

【问题讨论】:

    标签: r date dplyr lubridate


    【解决方案1】:

    这行得通吗:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      相关资源
      最近更新 更多