R:如何使用汇总并在分组数据上一起工作

Ira*_*kli 3 r dplyr tidyverse

在tidyverse中,汇总可用于具有单值函数的分组数据.例如

mtcars %>% group_by(cyl) %>% summarise(max(cos(mpg)))
Run Code Online (Sandbox Code Playgroud)

如果函数是矢量值,那么,如果我没有错,建议使用do.例如,do命令适用于phych包中的向量值函数'describe':

 library(psych)
 mtcars %>% group_by(cyl) %>% do(describe(.$mpg))
Run Code Online (Sandbox Code Playgroud)

如何同时将单值和向量值函数应用于分组数据?例如,如何将max(cos())和describe()同时应用于mpg列,并将输出作为一个数据帧?

akr*_*run 6

我们可以将输出describe放在a list之内summarise然后unnest

library(tidyverse)
mtcars %>% 
    group_by(cyl) %>%
    summarise(Cosmpg = max(cos(mpg)), list(describe(mpg))) %>%
    unnest
# A tibble: 3 x 15
#    cyl Cosmpg  vars     n  mean    sd median trimmed   mad   min   max range   skew kurtosis    se
#  <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>   <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>    <dbl> <dbl>
#1  4.00  0.743  1.00 11.0   26.7  4.51   26.0    26.4  6.52  21.4  33.9 12.5   0.259   -1.65  1.36 
#2  6.00  0.939  1.00  7.00  19.7  1.45   19.7    19.7  1.93  17.8  21.4  3.60 -0.158   -1.91  0.549
#3  8.00  0.989  1.00 14.0   15.1  2.56   15.2    15.2  1.56  10.4  19.2  8.80 -0.363   -0.566 0.684
Run Code Online (Sandbox Code Playgroud)