如何按组执行Wilcoxon检验并计算置信区间,用ggplot可视化?
按组执行Wilcoxon检验并绘制置信区间结果
问题描述
想按组执行wilcoxon.test并计算置信区间,之后用ggplot绘制伪中位数及其对应的置信区间,但编写的代码报错,不清楚如何保存结果供ggplot使用。
原始数据代码
zero <- sample(0:0, 50, replace = TRUE) small <- sample(1:5, 20, replace = TRUE) medium <- sample(5:25, 15, replace = TRUE) high <- sample(150:300, 5, replace = TRUE) f <- function(x){ return(data.frame(ID=deparse(substitute(x)), value=x)) } all <- bind_rows(f(zero), f(small), f(medium), f(high)) all <- as.data.frame(all[,-1]) names(all)[1] <- "value" all$group <- c("a", "b", "c")
尝试代码及错误
x <- ddply(all, .(group), function(x) {wilcox.test(all$value, conf.int=TRUE, conf.level=0.95)})
Error in list_to_dataframe(res, attr(.data, "split_labels"), .id, id_as_factor) :
Results must be all atomic, or all data frames
In addition: There were 12 warnings (use warnings() to see them)
解决方案
1. 修正数据分组问题
原始代码中all共有90行数据(50+20+15+5),但all$group仅赋值3个元素,会自动循环填充,导致分组逻辑错误。先修正分组:
library(dplyr) library(ggplot2) # 修正分组,对应四个数据组 all$group <- rep(c("a", "b", "c", "d"), times = c(50, 20, 15, 5))
2. 按组执行Wilcoxon检验并提取结果
使用dplyr按分组执行检验,提取伪中位数、置信区间上下限并整理成ggplot可用的数据框:
# 按组计算Wilcoxon检验结果 wilcox_results <- all %>% group_by(group) %>% summarize( # 执行一次检验并存储结果 test_out = list(wilcox.test(value, conf.int = TRUE, conf.level = 0.95)), # 提取需要的统计量 pseudo_median = test_out[[1]]$estimate, ci_low = test_out[[1]]$conf.int[1], ci_high = test_out[[1]]$conf.int[2] ) %>% # 移除临时存储的检验结果列表 select(-test_out)
3. 用ggplot绘制结果
基于整理好的结果数据框,绘制伪中位数及置信区间:
ggplot(wilcox_results, aes(x = group, y = pseudo_median)) + # 绘制伪中位数点 geom_point(size = 3, color = "#2c3e50") + # 绘制置信区间误差棒 geom_errorbar(aes(ymin = ci_low, ymax = ci_high), width = 0.2, color = "#2c3e50") + # 添加标题和坐标轴标签 labs( title = "各组伪中位数及95%置信区间", x = "分组", y = "伪中位数" ) + # 使用简洁主题 theme_minimal()
错误原因说明
- 原始代码中
wilcox.test(all$value)错误使用了全局数据集的value列,而非分组后的x$value,导致检验逻辑错误。 ddply要求分组函数返回原子向量或数据框,但wilcox.test直接返回的是列表对象,因此需要提取列表中的具体统计量并整理成数据框格式。
内容的提问来源于stack exchange,提问作者Nate
相关产品推荐
相关产品推荐

