Parallel wilcox.test using group_by and summarise

杀马特。学长 韩版系。学妹 提交于 2019-12-03 15:06:39

You can do this with base R (although the result is a cumbersome list):

by(df, df$id1, function(x) { wilcox.test(x~id2, data=x, paired=FALSE)$p.value })

or with dplyr:

ddply(df, .(id1), function(x) { wilcox.test(x~id2, data=x, paired=FALSE)$p.value })

  id1        V1
1   1 0.3095238
2   2 1.0000000
3   3 0.8412698
4   4 0.6904762
5   5 0.3095238

Your task will be easily accomplished using the do function (call ?do after loading the dplyr library). Using your data, the chain will look like this:

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)

output

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

Note I added the do function between the group_by and summarize.
I hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!