在R中基于多行列条件计算患者累计住院天数的实现方法
Hey there! Let's tackle this problem step by step. Since you mentioned patients might have multiple admissions, we'll need to group the data by patient ID first, then calculate the cumulative stay days properly. Below is a practical implementation based on common hospital data structures (I'll assume your dataframe includes patient IDs, admission dates, and discharge dates—adjust column names if yours differ).
1. 先模拟匹配场景的测试数据
Let's start with sample data that mirrors your real-world scenario (patients with multiple hospital stays):
library(dplyr) library(lubridate) # 模拟患者多次住院的数据集 df <- tibble( patient_id = c(1,1,2,2,2), admission_date = ymd(c("2023-01-05", "2023-03-10", "2023-02-01", "2023-04-15", "2023-06-20")), discharge_date = ymd(c("2023-01-12", "2023-03-18", "2023-02-07", "2023-04-22", "2023-06-25")) ) print(df)
2. 核心逻辑:计算累计住院天数
Here's the step-by-step code to add the cumulative stay days column:
df_with_cumulative <- df %>% # 第一步:确保日期列是标准日期格式(如果你的原始数据是字符型,必须先转换) mutate( admission_date = ymd(admission_date), discharge_date = ymd(discharge_date) ) %>% # 第二步:按患者ID分组,同时按入院日期排序(保证累计顺序符合时间线) group_by(patient_id) %>% arrange(admission_date, .by_group = TRUE) %>% # 第三步:计算单次住院的天数(入院当天算1天,所以要加1) mutate( single_stay_days = as.numeric(discharge_date - admission_date) + 1, # 第四步:累加单次住院天数,得到累计值 cumulative_stay_days = cumsum(single_stay_days) ) %>% ungroup() print(df_with_cumulative)
3. 特殊情况处理
- 缺失出院日期:如果部分记录没有出院日期,你可以用当前日期替代,或者标记为缺失:
df_with_cumulative <- df %>% mutate( # 用当前日期填充缺失的出院日期 discharge_date = if_else(is.na(discharge_date), today(), discharge_date) ) %>% # 后续步骤和上面一致...
- 大数据量优化:如果你的数据集很大,用
data.table会更高效:
library(data.table) setDT(df) df[, `:=`( admission_date = ymd(admission_date), discharge_date = ymd(discharge_date), single_stay_days = as.numeric(discharge_date - admission_date) + 1 )][order(admission_date), cumulative_stay_days := cumsum(single_stay_days), by = patient_id]
结果说明
The cumulative_stay_days column you get will show the total number of days a patient has spent in the hospital up to that specific admission. For example, patient 1's first stay is 8 days, second is 9 days, so their cumulative values will be 8 and 17 respectively.
内容的提问来源于stack exchange,提问作者Hussain Rahiminejad

