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

时间:2014-10-30 22:43:14

标签: r group-by dplyr split-apply-combine

我正在尝试使用dplyr执行以下操作:

 tapply(iris$Petal.Length, iris$Species, shapiro.test)

我想按照Speicies拆分Petal.Lengths并应用一个函数,在这种情况下shapiro.test.我读了这个SO question和其他很多页面。我有点能够使用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

将列“拆分”成组似乎正在起作用。但是将这些碎片传递给shapiro.test的方法仍然无法解决。我发现group_by拆分为不同。

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

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

以及

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

 # Error: expecting a single value

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

2 个答案:

答案 0 :(得分:6)

我可以看到两种方法,取决于你想要如何使用输出。您可以从shapiro.test中的summarise中提取p值。或者,您可以使用do并将每个测试的结果保存在列表中。

library(dplyr)

使用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

使用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

答案 1 :(得分:1)

如果您使用broom package中的tidy()功能,要将shapiro.test()的输出转换为data.frame,那么您可以使用do()

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

这会给你:

Source: local data frame [3 x 4]
Groups: Species [3]

Species statistic    p.value                      method
      <fctr>     <dbl>      <dbl>                      <fctr>
1     setosa 0.9549768 0.05481147 Shapiro-Wilk normality test
2 versicolor 0.9660044 0.15847784 Shapiro-Wilk normality test
3  virginica 0.9621864 0.10977537 Shapiro-Wilk normality test

这是改编自我的回复here