使用dplyr的group_by执行split-apply-combine

Ram*_*han 4 group-by r split-apply-combine dplyr

我想用来dplyr做以下事情:

 tapply(iris$Petal.Length, iris$Species, shapiro.test)
Run Code Online (Sandbox Code Playgroud)

我想通过Speicies拆分Petal.Lengths并应用一个函数,在这种情况下shapiro.test.我读了这个SO问题和其他许多页面.我有点能够将变量分成组,使用do:

iris %>%
  group_by(Species) %>%
  select(Petal.Length) %>%
  do(print(.$Petal.Length)) 

 [1] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 1.5 1.6 1.4 1.1 1.2
[16] 1.5 1.3 1.4 1.7 1.5 1.7 1.5 1.0 1.7 1.9 1.6 1.6 1.5 1.4 1.6
[31] 1.6 1.5 1.5 1.4 1.5 1.2 1.3 1.4 1.3 1.5 1.3 1.3 1.3 1.6 1.9
[46] 1.4 1.6 1.4 1.5 1.4
 [1] 4.7 4.5 4.9 4.0 4.6 4.5 4.7 3.3 4.6 3.9 3.5 4.2 4.0 4.7 3.6
[16] 4.4 4.5 4.1 4.5 3.9 4.8 4.0 4.9 4.7 4.3 4.4 4.8 5.0 4.5 3.5
[31] 3.8 3.7 3.9 5.1 4.5 4.5 4.7 4.4 4.1 4.0 4.4 4.6 4.0 3.3 4.2
[46] 4.2 4.2 4.3 3.0 4.1
Run Code Online (Sandbox Code Playgroud)

将列"拆分"成组似乎正在起作用.但是将这些碎片传递给shapiro.test的方法仍然无法解决.我看到这group_by分裂不同.

我尝试了很多变化,包括:

iris %>%
  group_by(Species) %>%
  select(Petal.Length) %>%
  summarise(shapiro.test)
Run Code Online (Sandbox Code Playgroud)

并且

iris %>%
  group_by(Species) %>%
  select(Petal.Length) %>%
  summarise_each(funs(shapiro.test))

 # Error: expecting a single value
Run Code Online (Sandbox Code Playgroud)

我怎样才能为每个物种的Petal.Lengths 进行三次dplyr运行shapiro.test()

aos*_*ith 6

我可以看到两种方法,具体取决于你想要如何使用输出.你可以从你拉出来只是p值shapiro.testsummarise.或者,您可以do在列表中使用并保存每个测试的结果.

library(dplyr)
Run Code Online (Sandbox Code Playgroud)

summarise,只取出p值:

iris %>%
    group_by(Species) %>%
    summarise(stest = shapiro.test(Petal.Length)$p.value)

     Species      stest
1     setosa 0.05481147
2 versicolor 0.15847784
3  virginica 0.10977537
Run Code Online (Sandbox Code Playgroud)

使用do:

tests = iris %>%
    group_by(Species) %>%
    do(test = shapiro.test(.$Petal.Length))

# Resulting list
tests$test

[[1]]

    Shapiro-Wilk normality test

data:  .$Petal.Length
W = 0.955, p-value = 0.05481


[[2]]

    Shapiro-Wilk normality test

data:  .$Petal.Length
W = 0.966, p-value = 0.1585


[[3]]

    Shapiro-Wilk normality test

data:  .$Petal.Length
W = 0.9622, p-value = 0.1098
Run Code Online (Sandbox Code Playgroud)