如何在R中计算ICU入院初始时间至24小时内的均值?
问题分析与解决方案
原代码的核心问题
- POSIXlt格式不兼容dplyr函数:
between()对POSIXlt类型时间支持不佳,POSIXlt是列表结构,算术运算和比较会出现异常,建议改用POSIXct格式。 - 分组逻辑错误:
group_by()中加入了Record_Time,导致每条记录单独成组,无法计算组内均值;且同一Encounter_ID的ICU_FIRST是唯一值,无需加入分组。 - 变量名大小写错误:数据集中的指标列是
Value,但代码中写的是value,R语言对大小写敏感。 - 管道符语法错误:部分
%>缺少末尾的%,正确写法应为%>%。 - 数据集名称不匹配:代码中调用了
df但实际数据集是test。 - 时间运算方式错误:POSIXlt类型直接加86400(秒)会导致结构异常,应先转成POSIXct再做时间加法。
修正后的dplyr解决方案
先修正时间格式,再调整分组和过滤逻辑:
library(dplyr) library(lubridate) # 简化时间运算,可选 # 将时间转为POSIXct格式(替代POSIXlt) test$ICU_FIRST <- as.POSIXct(test$ICU_FIRST, format = "%Y-%m-%d %H:%M:%S") test$Record_Time <- as.POSIXct(test$Record_Time, format = "%Y-%m-%d %H:%M:%S") # 计算ICU入院首24小时内的指标均值 result <- test %>% arrange(MRN, Encounter_ID, Record_Time) %>% group_by(Encounter_ID) %>% # 仅按Encounter_ID分组 filter(Record_Time >= ICU_FIRST & Record_Time <= ICU_FIRST + days(1)) %>% # 用days(1)直观表示24小时,也可替换为86400 summarise(mean_value = mean(Value, na.rm = TRUE)) # 注意变量名是Value,添加na.rm处理潜在缺失值 print(result)
运行结果:
# A tibble: 2 × 2 Encounter_ID mean_value <dbl> <dbl> 1 1 5.5 2 100 8.5
Base R解决方案
无需dplyr包,用原生R代码实现:
# 转换时间格式为POSIXct test$ICU_FIRST <- as.POSIXct(test$ICU_FIRST, format = "%Y-%m-%d %H:%M:%S") test$Record_Time <- as.POSIXct(test$Record_Time, format = "%Y-%m-%d %H:%M:%S") # 筛选ICU入院首24小时内的记录 filtered_data <- test[test$Record_Time >= test$ICU_FIRST & test$Record_Time <= test$ICU_FIRST + 86400, ] # 按Encounter_ID分组计算均值 result_base <- aggregate(Value ~ Encounter_ID, data = filtered_data, FUN = function(x) mean(x, na.rm = TRUE)) colnames(result_base)[2] <- "mean_value" print(result_base)
运行结果:
Encounter_ID mean_value 1 1 5.5 2 100 8.5
内容的提问来源于stack exchange,提问作者EtoiledeMoyenOrient
相关产品推荐
相关产品推荐

