在dplyr的组或因子上使用函数

问题描述

我想使用一个功能,例如shapiro.test()在数据集中的多个组上。

首先我尝试

library(tidyverse)
library(magrittr)

mtcars %>% group_by(cyl) %$% shapiro.test(wt)$p.value
#> [1] 0.09265499

但是,这并没有像我期望的那样遍历各个组。 然后,我尝试了一个将结果输出为数据帧的函数,因为这是在Stack Overflow上另一个问题的解决方法

checknorm <- function(x) {
  return(data.frame(P = shapiro.test(x)$p.value))
}

mtcars %>% group_by(cyl) %$% checknorm(wt)
#>            P
#> 1 0.09265499

使函数遍历group_by()传递的组的合适方法是什么?

解决方法

创建一个新列以存储每个组的p值:

library(dplyr)

mtcars %>% 
  group_by(cyl) %>%
  summarise(p_val = shapiro.test(wt)$p.value)

#   cyl   p_val
#  <dbl>   <dbl>
#1     4 0.570  
#2     6 0.131  
#3     8 0.00275