使用dplyr的group_by进行split-apply-combine [英] Use dplyr's group_by to perform split-apply-combine

查看:19
本文介绍了使用dplyr的group_by进行split-apply-combine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use dplyr to do the following:

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

我想按物种分割 Petal.Lengths,并应用一个函数,在本例中为 shapiro.test. 我读了这个 SO 问题 以及许多其他页面.我可以使用 do 将变量分成几组:

I want to split the Petal.Lengths by Speicies, and apply a function, in this case shapiro.test. I read this SO question and quite a number of other pages. I am sort of able to split the variable into groups, using 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_bysplit into 不同.

The 'splitting' of the column into groups seems to be working. But the way to pass the pieces to shapiro.test is still eluding me. I see that group_by is different from split into.

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

I tried lots of variations, including:

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?

How can I make dplyr run shapiro.test() thrice, once for the Petal.Lengths of each Species?

推荐答案

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

I could see two ways to do it, depending on how you want to use the output. You could pull out just the p-values from shapiro.test in summarise. Alternatively you could use do and save the results of each test in a list.

library(dplyr)

使用 summarise,只提取 p 值:

With summarise, pulling out just the p-values:

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

这篇关于使用dplyr的group_by进行split-apply-combine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆