代码之家  ›  专栏  ›  技术社区  ›  tic-toc-choc

用R按组检测重叠日期

  •  0
  • tic-toc-choc  · 技术社区  · 6 年前

    给定一个数据集

    enter image description here

    structure(list(intervention = c("Self Isolation", "Lockdown Low", 
    "Lockdown Low", "Self Isolation", "Social Distancing", "Lockdown Low", 
    "Social Distancing", "Handwashing"), date_start = structure(c(17897, 
    17957, 18444, 17987, 17897, 17532, 17942, 18018), class = "Date"), 
        date_end = structure(c(17956, 18262, 18475, 18017, 17956, 
        18053, 18017, 18048), class = "Date")), class = c("tbl_df", 
    "tbl", "data.frame"), row.names = c(NA, -8L))
    

    我如何检查任何“干预”是否有重叠的日期? 在这个例子中,所有的干预都是好的 但是 “社交距离”和“低封锁”

    理想的输出是一个数据帧,每行一次干预,一列填充 TRUE / FALSE 取决于干预是否有重叠。

    enter image description here

    (tidyverse解决方案需额外加分。)

    0 回复  |  直到 6 年前
        1
  •  1
  •   akrun    6 年前

    我们可以做一个 summarise

    library(dplyr)
    df1 %>%
        arrange(intervention, date_start, date_end) %>% 
        group_by(intervention) %>%
        summarise(overlapping = any(date_start < lag(date_end, 
             default = first(date_end)) & row_number() != 1))
    # A tibble: 4 x 2
    #  intervention      overlapping
    #  <chr>             <lgl>      
    #1 Handwashing       FALSE      
    #2 Lockdown Low      TRUE       
    #3 Self Isolation    FALSE      
    #4 Social Distancing TRUE