缘由
统计是生信的基石之一
碎碎念
要爱一个具体的人,不要爱一个抽象的人; 要爱生活,不要爱生活的意义。 ——《卡拉马佐夫兄弟》
Ref
Kruskal-Wallis Test in R: The Ultimate Guide - Datanovia
解读
当我们想比较三组或以上样本的中位数差异,但数据不满足正态或方差齐性时,
Kruskal–Wallis 检验就是非参数界的“方差分析”替代方案。
🔹 1. 准备数据与环境
library(tidyverse)
library(ggpubr)
library(rstatix)
set.seed(1234)
PlantGrowth %>% sample_n_by(group, size = 1)我们使用内置数据集
PlantGrowth,共有三组(ctrl, trt1, trt2),记录植物在不同处理下的生长重量。
🔹 2. 查看分组描述统计
PlantGrowth %>%
group_by(group) %>%
get_summary_stats(weight, type = "common")输出平均数、标准差、标准误等指标,先感受一下各组的分布差异。
🔹 3. 初步可视化:箱线图查看分布
ggboxplot(PlantGrowth, x = "group", y = "weight")这一步帮助我们直观了解三组数据的集中趋势与离散程度。
🔹 4. 总体差异检验:Kruskal–Wallis
res.kruskal <- PlantGrowth %>% kruskal_test(weight ~ group)
res.kruskalKruskal–Wallis 检验的原假设:三组总体的中位数相等。
若 p < 0.05,说明至少有一组显著不同。
例如结果:
Kruskal-Wallis chi-squared = 4.82, df = 2, p = 0.089
p > 0.05 → 没有显著差异(这里只是示例,真实分析仍需根据数据解释)。
🔹 5. 计算效应量(Effect Size)
PlantGrowth %>% kruskal_effsize(weight ~ group)量化差异强度(η² 类型),不是仅仅看显著性。
0.01 小、0.06 中、0.14 大效应。
🔹 6. 事后检验(Post-hoc Test)
若总体差异显著,需要找出哪两组之间不同。
✅ 方法1:Dunn 检验(推荐)
pwc <- PlantGrowth %>%
dunn_test(weight ~ group, p.adjust.method = "bonferroni")
pwcDunn 检验适用于 Kruskal–Wallis 的非参数事后比较。
p.adjust.method = "bonferroni"表示多重比较校正。
✅ 方法2:成对 Wilcoxon 检验(备用)
pwc2 <- PlantGrowth %>%
wilcox_test(weight ~ group, p.adjust.method = "bonferroni")
pwc2🔹 7. 美化输出:添加显著性标注到图中
pwc <- pwc %>% add_xy_position(x = "group")
ggboxplot(PlantGrowth, x = "group", y = "weight") +
stat_pvalue_manual(pwc, hide.ns = TRUE) +
labs(
subtitle = get_test_label(res.kruskal, detailed = TRUE),
caption = get_pwc_label(pwc)
)思路
| 步骤 | 目的 | 函数 |
|---|---|---|
| ① 数据准备 | 检查数据结构 | sample_n_by() |
| ② 描述统计 | 了解各组分布 | get_summary_stats() |
| ③ 可视化初探 | 直观比较中位数 | ggboxplot() |
| ④ Kruskal–Wallis 检验 | 判断是否存在组间差异 | kruskal_test() |
| ⑤ 效应量计算 | 衡量差异强度 | kruskal_effsize() |
| ⑥ 事后比较 | 识别具体差异组 | dunn_test() / wilcox_test() |
| ⑦ 图形展示 | 自动添加显著性 | stat_pvalue_manual() |