【问题标题】:How do I determine in R if a date interval overlaps another date interval for the same individual in a data frame?如何在 R 中确定日期间隔是否与数据框中同一个人的另一个日期间隔重叠?
【发布时间】:2021-04-27 18:28:52
【问题描述】:

我有一个医院索赔数据集。每一行都是一个声明,我有以下列:患者 ID、开始日期和结束日期。如果患者多次到医院就诊,他们可以有多次索赔。我正在尝试根据数据集中的所有索赔计算患者在医院度过的总时间。

library(tibble)
df <- tribble(
  ~id, ~start_date, ~end_date,
  "100003186", "2011-06-18", "2011-08-09",
  "100003186", "2011-06-18", "2011-08-23",
  "100003186", "2011-12-14", "2011-12-16",
  "100003186", "2014-09-14", "2014-09-17",
  "100003186", "2014-09-10", "2014-09-18",
  "100003187", "2011-11-18", "2011-11-30",
  "100003187", "2011-11-18", "2011-11-23",
)

问题在于某些声明的日期重叠。例如,对于 id=="100003186",第一个索赔是从日期 2011-06-18 到 2011-08-09,但是这个时间段已经包含在第二个索赔中,从日期 2011-06-18 到 2011 -08-23.

如何删除时间间隔包含在同一个人 (id) 的另一个索赔间隔内的行?

这个问题提供了一个可能的解决方案,但我想通过 id 来实现它:R: Determine if each date interval overlaps with all other date intervals in a dataframe

【问题讨论】:

标签: r lubridate


【解决方案1】:

您可以使用%within%group_by()

library(tidyverse)
library(purrr)
library(lubridate)
df %>%
  group_by(id) %>%
  mutate(Int = interval(start_date, end_date), 
                within = map(seq_along(Int), function(x){
           y = setdiff(seq_along(Int), x)
           #The interval is within any other intervals (in the group)
           return(any(Int[x] %within% Int[y]))
           
         })
  ) %>% 
  #and now remove those that are within another
  filter(within == FALSE)

查看lubridate 上的文档,里面有很多简洁的小功能!

【讨论】:

  • 嗨@dyrland,感谢您的回答!但是,在上面的代码中运行它时,出现以下错误。你知道为什么会这样吗?错误:mutate() 输入 overlaps 有问题。 x 在为函数“%within%”选择方法时评估参数“b”时出错:找不到对象“y”。
  • 编辑:我也不想删除所有重叠。我只想删除另一个区间中包含的区间。
  • 哎呀!在从链接的答案中清除代码时,我清除了生成y 的行。我已经编辑了代码。我在末尾添加了一个过滤器,该过滤器删除了间隔完全在另一个间隔内的行。我想如果你想的话,你可以将该区间转换为 null...
【解决方案2】:

按开始日期排序,然后查找结束日期小于前一个日期的任何日期。

library(dplyr)
df %>% 
      arrange(id, start_date) %>% 
      group_by(id) %>% 
      mutate(contained = end_date <= lag(end_date)) %>%
      filter(!contained | is.na(contained))

这是“弱遏制”,即它可能会删除一些具有相同开始日期和/或结束日期的部分。如果您不想这样,请酌情调整within 计算。最后一行中的 is.na 调用确保我们不会删除每个 ID 的第一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2019-04-21
    相关资源
    最近更新 更多