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

R处理药物处方数据:区分同ID同药处方段并计算随访总费用

药物处方分段与费用统计分析问题

基础信息

  • 分析场景为带日期维度的药物处方数据分析,示例数据结构代码如下:
structure(list(id = c(4L, 4L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 
6L), claim = c(1L, 2L, 1L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L), start_date = structure(c(12267, 
12298, 12626, 12818, 12846, 12877, 12907, 12938, 13091, 13121, 
13152), class = "Date"), drug = c("a", "a", "a", "b", "b", "a", 
"a", "a", "a", "a", "b"), total.price = c(100L, 100L, 100L, 100L, 
100L, 100L, 100L, 100L, 100L, 100L, 100L), dose = c(1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), IBD = c("CD", "CD", "CD", "CD", 
"CD", "CD", "CD", "CD", "CD", "CD", "CD"), naivety = c(1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1), diff_drug = c(0, 0, 0, 0, 0, 1, 0, 
0, 0, 0, 1)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -11L), groups = structure(list(id = 4:6, 
    .rows = structure(list(1:2, 3L, 4:11), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE))
  • 初始分析目标:计算每个id对应各段药物处方的开始日期与结束日期,判断逻辑为:
    • 若变量discontinuation==1,该受试者对应处方的结束日期取停药日期
    • 若discontinuation == 0,结束日期取处方记录的最晚start_date(即max(start_date))

已尝试的实现代码

bio_naive <- bio_naive %>% arrange(id,start_date) %>%  mutate(Diff = lead(start_date) - (start_date))

bio_naive <- bio_naive %>% group_by(id, drug) %>% mutate(discontinuation = ifelse(Diff > 90, '1', '0')) 

bio_naive$discontinuation[is.na(bio_naive $discontinuation)] <- 0

bio_naive %>%
  group_by(id,drug) %>% 
  summarise(discont=max(discontinuation), start = min(start_date, na.rm = TRUE), dc_final_date = if_else(any(discontinuation == 1), start_date[match(1, discontinuation)], max(start_date)))

现存问题

上述代码运行后未达到预期效果:id为6、drug为b的两段独立药物处方被错误合并统计,无法正确拆分两段独立的drug b处方记录。

待解决问题

  1. 如何区分id=6对应的两段drug b处方,实现同id下同种药物不同独立处方段的正确拆分?
  2. 如何编写代码,按id、药物、处方段分组,计算随访期(从处方开始日期到dc_final_date)内的total.price总和?

预期结果参考

预期结果示意图


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 10:42:21