【问题标题】:How to determine difference in days between two dates across two columns and and two rows by group using R?如何使用 R 确定跨两列和两行的两个日期之间的天数差异?
【发布时间】:2022-11-17 12:08:05
【问题描述】:

我希望通过两列和两行的组来确定天数差异。基本上从结束日减去后续行中的后续开始日,并将差异记录为数据框中的新列,并在识别新组 (ID) 时重新开始。

Start_Date   End_Date     ID   
  
2014-05-09   2015-05-08   01
2015-05-09   2016-05-08   01 
2016-05-11   2017-05-10   01
2017-05-11   2018-05-10   01
2016-08-29   2017-08-28   02
2017-08-29   2018-08-28   02

结果应该类似于下表。

Start_Date   End_Date     ID   Days_Difference 
  
2014-05-09   2015-05-08   01         NA
2015-05-09   2016-05-08   01         01
2016-05-11   2017-05-10   01         03
2017-05-11   2018-05-10   01         01
2016-08-29   2017-08-28   02         NA
2017-08-29   2018-08-28   02         01

本质上,我想计算结束日期与其左对角线开始日期跨组 (ID) 的差异。我真的很难过这个。我不认为我的代码会有帮助。任何使用 tidyverse、data.table 或 base R 的解决方案都将不胜感激!

【问题讨论】:

    标签: r date data.table tidyverse lubridate


    【解决方案1】:

    分组后我们可能会得到'End_Days'和'Start_Days'的lead之间的差异

    library(dplyr)
    df1 <- df1 %>%
       mutate(across(ends_with("Date"), as.Date)) %>%
       group_by(ID) %>% 
       mutate(Days_Difference = as.numeric(lag(lead(Start_Date) - End_Date))) %>% 
       ungroup
    

    -输出

    df1
    # A tibble: 6 × 4
      Start_Date End_Date      ID Days_Difference
      <date>     <date>     <int>           <dbl>
    1 2014-05-09 2015-05-08     1              NA
    2 2015-05-09 2016-05-08     1               1
    3 2016-05-11 2017-05-10     1               3
    4 2017-05-11 2018-05-10     1               1
    5 2016-08-29 2017-08-28     2              NA
    6 2017-08-29 2018-08-28     2               1
    

    或者与data.table类似的逻辑

    library(data.table)
    setDT(df1)[, Days_Difference := 
        as.numeric(shift(shift(as.IDate(Start_Date), type = "lead") - 
           as.IDate(End_Date))), ID]
    

    -输出

    > df1
       Start_Date   End_Date    ID Days_Difference
           <char>     <char> <int>           <num>
    1: 2014-05-09 2015-05-08     1              NA
    2: 2015-05-09 2016-05-08     1               1
    3: 2016-05-11 2017-05-10     1               3
    4: 2017-05-11 2018-05-10     1               1
    5: 2016-08-29 2017-08-28     2              NA
    6: 2017-08-29 2018-08-28     2               1
    

    数据

    df1 <- structure(list(Start_Date = c("2014-05-09", "2015-05-09", "2016-05-11", 
    "2017-05-11", "2016-08-29", "2017-08-29"), End_Date = c("2015-05-08", 
    "2016-05-08", "2017-05-10", "2018-05-10", "2017-08-28", "2018-08-28"
    ), ID = c(1L, 1L, 1L, 1L, 2L, 2L)), class = "data.frame", 
    row.names = c(NA, 
    -6L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 2022-12-01
      • 2011-03-19
      • 2013-07-24
      • 2010-12-09
      相关资源
      最近更新 更多