gpt4 book ai didi

r - 使用 group_by 并行 wilcox.test 并总结

转载 作者:行者123 更新时间:2023-12-04 12:08:28 25 4
gpt4 key购买 nike

必须有 R-ly 方式来调用 wilcox.test使用 group_by 并行进行多个观察。我花了很多时间阅读这篇文章,但仍然无法确定调用 wilcox.test 的电话。就可以了。下面的示例数据和代码,使用 magrittr管道和 summarize() .

library(dplyr)
library(magrittr)

# create a data frame where x is the dependent variable, id1 is a category variable (here with five levels), and id2 is a binary category variable used for the two-sample wilcoxon test
df <- data.frame(x=abs(rnorm(50)),id1=rep(1:5,10), id2=rep(1:2,25))

# make sure piping and grouping are called correctly, with "sum" function as a well-behaving example function
df %>% group_by(id1) %>% summarise(s=sum(x))
df %>% group_by(id1,id2) %>% summarise(s=sum(x))

# make sure wilcox.test is called correctly
wilcox.test(x~id2, data=df, paired=FALSE)$p.value

# yet, cannot call wilcox.test within pipe with summarise (regardless of group_by). Expected output is five p-values (one for each level of id1)
df %>% group_by(id1) %>% summarise(w=wilcox.test(x~id2, data=., paired=FALSE)$p.value)
df %>% summarise(wilcox.test(x~id2, data=., paired=FALSE))

# even specifying formula argument by name doesn't help
df %>% group_by(id1) %>% summarise(w=wilcox.test(formula=x~id2, data=., paired=FALSE)$p.value)

错误调用会产生此错误:
Error in wilcox.test.formula(c(1.09057358373486, 
2.28465932554436, 0.885617572657959, : 'formula' missing or incorrect

谢谢你的帮助;我希望它对其他有类似问题的人也有帮助。

最佳答案

使用 do 函数可以轻松完成您的任务(在加载 dplyr 库后调用 ?do)。使用您的数据,链将如下所示:

df <- data.frame(x=abs(rnorm(50)),id1=rep(1:5,10), id2=rep(1:2,25))
df <- tbl_df(df)
res <- df %>% group_by(id1) %>%
do(w = wilcox.test(x~id2, data=., paired=FALSE)) %>%
summarise(id1, Wilcox = w$p.value)

输出
res
Source: local data frame [5 x 2]

id1 Wilcox
(int) (dbl)
1 1 0.6904762
2 2 0.4206349
3 3 1.0000000
4 4 0.6904762
5 5 1.0000000

注意我在 group_by 和 summarise 之间添加了 do 函数。
我希望它有所帮助。

关于r - 使用 group_by 并行 wilcox.test 并总结,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34581343/

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