如何在R中对分组数据按列执行wilcox.test并添加p值到新行
R实现逐列分组Wilcoxon检验并添加p值行
首先构造示例数据df1:
set.seed(12345) df1 <- data.frame( group = c(rep("apple", 4), rep("pear",6)), a = rnorm(10, 0, 0.4), b = rnorm(10, 0, 0.2), c = rnorm(10, 0, 0.7), d = rnorm(10, 0, 0.9), e = rnorm(10, 0, 0.5) )
方法1:基础R实现
# 拆分两组的数值列数据 apple_num <- df1[df1$group == "apple", -1] pear_num <- df1[df1$group == "pear", -1] # 逐列计算wilcox检验p值 p_values <- sapply(colnames(apple_num), function(col) { wilcox.test(apple_num[[col]], pear_num[[col]])$p.value }) # 构造p值行并合并到原数据 p_row <- c(group = "wilcox.test", round(p_values, 9)) df2 <- rbind(df1, as.data.frame(as.list(p_row), stringsAsFactors = FALSE)) # 可选:将数值列转换回数值类型(合并后默认是字符) df2[, 2:ncol(df2)] <- lapply(df2[, 2:ncol(df2)], as.numeric)
方法2:tidyverse简洁实现
library(dplyr) # 计算各列p值 p_row <- df1 %>% summarise( across(a:e, ~wilcox.test(.x[group == "apple"], .x[group == "pear"])$p.value) ) %>% mutate(group = "wilcox.test", .before = 1) # 合并得到最终结果 df2 <- bind_rows(df1, p_row)
打印df2即可得到你示例中的结果:
group a b c d e 1 apple 0.2342115 -0.0232496 0.545735 0.73068586 0.564255 2 apple 0.2837864 0.3634624 1.019050 1.97715019 -1.190179 3 apple -0.0437213 0.0741256 -0.451030 1.84427130 -0.530133 4 apple -0.1813989 0.1040433 -1.087196 1.46920108 0.468570 5 pear 0.2423550 -0.1501064 -1.118397 0.22884407 0.427226 6 pear -0.7271824 0.1633800 1.263568 0.44206945 0.730365 7 pear 0.2520394 -0.1772715 -0.337153 -0.29167792 -0.706549 8 pear -0.1104736 -0.0663155 0.434266 -1.49584522 0.283702 9 pear -0.1136639 0.2241425 0.428486 1.59096047 0.291594 10 pear -0.3677288 0.0597447 -0.113618 0.02322094 -0.653399 11 wilcox.test 0.3937686 0.2864220 1.000000 0.03300626 1.000000
注意:如果需要调整检验类型(如单侧检验),可以在
wilcox.test中添加alternative参数设置。
内容的提问来源于stack exchange,提问作者Sylvia Rodriguez
相关产品推荐
相关产品推荐

