如何对存放在列表中的tibble及其列、值执行批量处理与分析操作
首先将所有依赖包加载语句放在脚本最开头,避免批量调用时重复加载报错:
library(tidyverse) library(psych) # 对应describe()函数 library(epiR) library(BlandAltmanLeh)
1. 批量拆分列表中的所有tibble
推荐使用嵌套列表存储拆分结果,结构清晰也方便后续继续批量处理,你也可以选择将拆分后的数据直接写入全局环境:
# 先统一定义拆分规则:分段名称对应行范围 split_rules <- list( Sitting = 1:12, Standing = 13:26, LigEx = 27:35, VigEx = 36:42, After = 43:54 ) # 批量拆分,生成嵌套列表Splitted_Data_List # 第一层对应原Data_List的每个数据集,第二层对应5个拆分后的分段 Splitted_Data_List <- lapply(Data_List, function(df) { lapply(split_rules, function(row_range) df[row_range, ]) }) # 可选:将所有拆分后的数据批量赋值到全局环境,命名规则为「原数据集名_分段名」 for (data_idx in seq_along(Splitted_Data_List)) { data_prefix <- names(Splitted_Data_List)[data_idx] %||% paste0("data_", data_idx) for (split_name in names(split_rules)) { assign( x = paste0(data_prefix, "_", split_name), value = Splitted_Data_List[[data_idx]][[split_name]], envir = .GlobalEnv ) } }
2. 批量执行统计分析与绘图
将单数据集的处理逻辑封装为自定义函数,再用lapply批量应用到所有tibble即可,返回的结果列表会包含每个数据集的所有统计结果和绘图对象:
注:你原来的单数据集代码中
cor.test(df)写法有误,cor.test不能直接传入整个数据框,已修正为传入两个待分析的数值向量。
# 自定义单数据集处理函数 process_single_df <- function(df, df_name = "未命名数据集") { # 描述性统计 desc_temp <- describe(df$Temperature) desc_core <- describe(df$Temp_core) # Pearson相关分析 pearson_res <- cor.test(df$Temp_core, df$Temperature) # Lin一致性相关系数分析 lin_res <- epi.ccc( df$Temp_core, df$Temperature, ci = "z-transform", conf.level = 0.95, rep.measure = FALSE ) # 温度变化折线图 mdata <- reshape2::melt(df, id = "Time") line_plot <- ggplot(data = mdata, aes(x = Time, y = value)) + geom_point(aes(group = variable, color = variable)) + geom_line(aes(group = variable, color = variable)) + labs(title = paste0(df_name, " 温度变化折线图")) + theme(plot.title = element_text(hjust = 0.5)) # Bland-Altman一致性图 ba_plot <- bland.altman.plot( df$Temp_core, df$Temperature, graph.sys = "ggplot2" ) + labs(title = paste0(df_name, " 温度一致性Bland-Altman图")) + theme(plot.title = element_text(hjust = 0.5)) # 打包返回所有结果 return(list( desc_Temperature = desc_temp, desc_Temp_core = desc_core, pearson_result = pearson_res, lin_ccc_result = lin_res, line_plot = line_plot, bland_altman_plot = ba_plot )) } # 批量应用到Data_List的所有tibble Analysis_Results <- lapply(seq_along(Data_List), function(i) { df_name <- names(Data_List)[i] %||% paste0("数据集", i) process_single_df(Data_List[[i]], df_name) }) # 给结果列表添加对应名称,方便后续调用 names(Analysis_Results) <- names(Data_List) %||% paste0("数据集", seq_along(Data_List))
结果调用示例
- 查看第1个数据集的Lin一致性相关系数结果:
Analysis_Results[[1]]$lin_ccc_result - 导出第2个数据集的折线图:
ggsave("数据集2折线图.png", Analysis_Results[[2]]$line_plot, width = 8, height = 6) - 遍历所有数据集批量导出Bland-Altman图:
for (i in seq_along(Analysis_Results)) { ggsave( filename = paste0(names(Analysis_Results)[i], "_BA图.png"), plot = Analysis_Results[[i]]$bland_altman_plot, width = 7, height = 5 ) }
内容的提问来源于stack exchange,提问作者GZM97
相关产品推荐
相关产品推荐

