合并R中的连续日期范围

时间:2018-12-17 16:56:42

标签: r

我想将观察结果合并为连续的(涵盖天数,没有间隔)日期范围。每个patid在结果数据帧中可能有多个范围,我知道可以通过循环来完成,但是有没有有效的方法来处理此任务?请注意,此处的时间间隔不重叠,并且start_date在增加。 enter image description here

数据在这里(我使用R:dput,您可以在R中复制并分配给您的对象):

structure(list(patid = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
2L, 3L, 3L, 3L), start_date = structure(c(1L, 2L, 3L, 4L, 5L, 
1L, 2L, 3L, 8L, 9L, 6L, 7L, 10L), .Label = c("1/1/2010", "2/1/2010", 
"3/1/2010", "4/1/2010", "5/1/2010", "5/6/2011", "7/1/2012", "8/1/2010", 
"9/1/2010", "9/1/2012"), class = "factor"), end_date = structure(c(1L, 
3L, 4L, 5L, 6L, 1L, 3L, 4L, 8L, 10L, 7L, 9L, 2L), .Label = c("1/31/2010", 
"12/1/2012", "2/28/2010", "3/31/2010", "4/30/2010", "5/31/2010", 
"6/15/2011", "8/31/2010", "8/31/2012", "9/30/2010"), class = "factor")), class = "data.frame", row.names = c(NA, 
-13L))

1 个答案:

答案 0 :(得分:1)

一种for (i in c('base','up',’down’))) { colnames(get(paste0("profile_",i)))[2] <- paste0("Probability_", i ) } 方法(使用data.table可提高可读性)(功能强大的版本):

magrittr

根据您的情况输出:

library(data.table)
library(magrittr)

calc_cummax <- function(x) (setattr(cummax(unclass(x)), "class", c("Date", "IDate")))

df_merged <- setDT(df) %>%
  .[, `:=` (cont_start = as.Date(as.character(start_date), "%m/%d/%Y"),
            cont_end = as.Date(as.character(end_date), "%m/%d/%Y"))] %>%
  .[order(patid, start_date),] %>%
  .[, max_until_now := shift(calc_cummax(cont_end)), by = patid] %>%
  .[, lead_max := shift(max_until_now, type = "lead"), by = patid] %>%
  .[is.na(max_until_now), max_until_now := lead_max, by = patid] %>%
  .[(max_until_now + 1L) >= cont_start, gap_between_contracts := 0, by = patid] %>% 
  .[(max_until_now + 1L) < cont_start, gap_between_contracts := 1, by = patid] %>%
  .[is.na(gap_between_contracts), gap_between_contracts := 0] %>% 
  .[, ("fakeidx") := cumsum(gap_between_contracts), by = patid] %>%
  .[, .(cont_start = min(cont_start), cont_end = max(cont_end)), by = .(patid, fakeidx)] %>% 
  .[, ("fakeidx") := NULL]

一种 patid cont_start cont_end 1: 1 2010-01-01 2010-05-31 2: 2 2010-01-01 2010-03-31 3: 2 2010-08-01 2010-09-30 4: 3 2011-05-06 2011-06-15 5: 3 2012-07-01 2012-12-01 方法(非健壮的简单版本):

tidyverse

输出:

library(tidyverse)

df %>%
  mutate(
    cont_start = as.Date(as.character(start_date), "%m/%d/%Y"),
    cont_end = as.Date(as.character(end_date), "%m/%d/%Y")
  ) %>%
  arrange(patid, cont_start) %>%
  group_by(patid) %>%
  mutate(
    idx = cumsum(coalesce(as.numeric(cont_start != (lag(cont_end) + 1)), 0))
  ) %>%
  group_by(patid, idx) %>%
  summarise(
    cont_start = min(cont_start),
    cont_end = max(cont_end)
  ) %>% select(-idx)

您的情况下的输出是相同的,但是如果在任何时候发生序列中的开始日期都比结束日期晚的开始日期,则您需要继续执行第一种(可靠的)方法(当然,如果您不认为这是一个错误)。

在这种情况下,健壮性与# A tibble: 5 x 3 # Groups: patid [3] patid cont_start cont_end <int> <date> <date> 1 1 2010-01-01 2010-05-31 2 2 2010-01-01 2010-03-31 3 2 2010-08-01 2010-09-30 4 3 2011-05-06 2011-06-15 5 3 2012-07-01 2012-12-01 data.table无关(您也可以通过重写tidyverse版本来使用calc_cummax函数,但是您需要加载tidyverse)。