gpt4 book ai didi

r - 多个 Wilcox 测试作为 R 中的循环

转载 作者:行者123 更新时间:2023-12-02 09:24:54 24 4
gpt4 key购买 nike

我的数据集包含

cb <- data.frame(group = ("A", "B", "C", "D", "E"), 
WC = runif(100, 0, 100),
Ana = runif(100, 0, 100),
Clo = runif(100, 0, 100))

str(cb)
data.frame: 66936 obs of 89 variables:
$group: Factor w/ 5 levels "A", "B", "C" ...
$WC: int 19 28 35 92 10 23...
$Ana: num 17.2 48 35.4 84.2
$ Clo: num 37.2 12.1 45.4 38.9
....

现在我想对 $group 执行多个 Wilcox 测试,使其最终看起来像这样:

commands: 
wilcox.test(cb$WC[cb$group == "A"], cb$WC[cb$group == "B"])
wilcox.test(cb$WC[cb$group == "A"], cb$WC[cb$group == "C"])
wilcox.test(cb$WC[cb$group == "A"], cb$WC[cb$group == "D"])
wilcox.test(cb$WC[cb$group == "A"], cb$WC[cb$group == "E"])
....

inserting the p-value:
WC A B C D E
A 1 0.12 0.03 0.2 0.42
B 0.12 1 0.1 0.07 0.1
C 0.03 0.1 1 0.2 0.3
D 0.2 0.07 0.2 1 0.1
E 0.42 0.1 0.3 0.1 1

Ana A B C D E
A 1 0.12 0.2 0.39 0.1
B 0.12 1 0.1 0.07 0.1
C ...
D
E

...

我有一个先前问题的 for 循环,multiple t-tests ,但我很难使其适应这项任务,因为 Wilcox-Test 的设计非常不同。这是我用于 t 测试的 for 循环:

res <- matrix(NA, ncol=5, 
dimnames=list(NULL, c("group", "col", "statistic", "estimate", "p.value")))

gr <- levels(cb$group)

for(cl in 2:ncol(cb)){
for(grp in gr){
temp <- cb[cb$group == grp, cl]
res <- rbind(res, c(grp, colnames(cb)[cl],
unlist(t.test(temp, mu = mean(cb[,cl]), alternative="two.sided"))[c(1, 5, 3)]))
}
}

您知道如何更改此 for 循环来执行 wilcox 测试吗?

最佳答案

原始数据:

set.seed(1L)
cb <- data.frame(group = factor(c("A", "B", "C", "D", "E")),
WC = runif(100, 0, 100),
Ana = runif(100, 0, 100),
Clo = runif(100, 0, 100))

代码:

library(purrr)

combins <- combn(levels(cb$group), 2)

params_list <- split(as.vector(combins), rep(1:ncol(combins), each = nrow(combins)))

model_wc <- map(.x = params_list,
.f = ~ wilcox.test(formula = WC ~ group,
data = subset(cb, group %in% .x)))

model_ana <- map(.x = params_list,
.f = ~ wilcox.test(formula = Ana ~ group,
data = subset(cb, group %in% .x)))

model_clo <- map(.x = params_list,
.f = ~ wilcox.test(formula = Clo ~ group,
data = subset(cb, group %in% .x)))

wilcox_pvals <- do.call(cbind, list(t(data.frame(map(.x = model_wc, .f = "p.value"))),
t(data.frame(map(.x = model_ana, .f = "p.value"))),
t(data.frame(map(.x = model_clo, .f = "p.value")))))

row.names(wilcox_pvals) <- unlist(map(.x = params_list, .f = ~ paste0(.x, collapse = "")))

colnames(wilcox_pvals) <- names(cb)[2:4]

输出:

> wilcox_pvals
# WC Ana Clo
# AB 0.7380622 0.52909692 0.75835096
# AC 0.9466955 0.41352631 0.32726184
# AD 0.6395139 0.79940719 0.30125264
# AE 0.8619871 0.34078485 0.04595423
# BC 0.9680024 0.63951388 0.18263084
# BD 0.8410127 0.38341328 0.12741907
# BE 0.7994072 0.10807707 0.01809358
# CD 0.7994072 0.21096433 0.94669547
# CE 0.7179503 0.03751918 0.38341328
# DE 0.7788036 0.63951388 0.30125264

关于r - 多个 Wilcox 测试作为 R 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38707266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com