You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并重叠或间隔≤5天的患者治疗起止日期(R语言)

解决方案:合并患者重叠/间隔小于5天的治疗时段

以下是针对需求的完整R语言实现,可直接运行得到预期结果:

library(dplyr)
library(lubridate)

# 加载原始数据
df <- read.table(text="
   ID   Start_Date     End_Date
    1     05-06-18       05-10-18
    1     05-08-18       05-14-18  
    1     05-16-18       05-25-18
    1     06-28-19       07-02-19
    1     07-03-19       07-08-19
    2     04-20-18       04-23-18
    2     07-20/18       07-25-18 
    2     07-26-18       07-30-18 
    3     05-14-17       05-29-17", 
                stringsAsFactors=FALSE, header=TRUE)

# 1. 统一日期格式并转换为标准Date类型
df_clean <- df %>%
  mutate(
    # 替换日期中的斜杠为横杠,统一格式
    Start_Date = gsub("/", "-", Start_Date),
    End_Date = gsub("/", "-", End_Date),
    # 将字符型日期转换为Date对象(格式为月-日-两位年)
    Start_Date = mdy(Start_Date),
    End_Date = mdy(End_Date)
  )

# 2. 按ID分组,识别并合并符合条件的时段
merged_df <- df_clean %>%
  arrange(ID, Start_Date) %>%  # 按ID和起始日期排序
  group_by(ID) %>%
  mutate(
    # 生成合并组ID:当前时段起始日 > 上一时段结束日+4天则开启新组
    group_id = cumsum(
      ifelse(row_number() == 1, 1, Start_Date > lag(End_Date) + days(4))
    )
  ) %>%
  group_by(ID, group_id) %>%
  summarise(
    Start_Date = min(Start_Date),  # 取组内最早起始日
    End_Date = max(End_Date),      # 取组内最晚结束日
    .groups = "drop"
  ) %>%
  # 转换回原日期格式(月-日-两位年)
  mutate(
    Start_Date = format(Start_Date, "%m-%d-%y"),
    End_Date = format(End_Date, "%m-%d-%y")
  )

# 输出结果
print(merged_df)

执行结果

ID Start_Date End_Date
1  1   05-06-18 05-25-18
2  1   06-28-19 07-08-19
3  2   04-20-18 07-30-18
4  3   05-14-17 05-29-17

核心逻辑说明

  1. 日期预处理:解决原始数据中日期格式不统一的问题(存在/和-两种分隔符),转换为标准Date类型才能进行日期运算。
  2. 分组标记:通过cumsum和lag函数判断当前时段是否需要与上一时段合并:若当前起始日与上一时段结束日的间隔≥5天,则作为新组;否则归为同一组。
  3. 合并计算:对每个分组取最早的起始日期和最晚的结束日期,完成时段合并。

内容的提问来源于stack exchange,提问作者Ian Parzyszek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 09:11:20