汇总不同聚合级别的数据-R和tidyverse

Ree*_*eza 6 r group-summaries dplyr tidyverse

我正在创建一堆基本状态报告,而我发现乏味的事情之一是向所有表添加总计行。我目前正在使用Tidyverse方法,这是我当前代码的一个示例。我正在寻找的是默认包含一些不同级别的选项。

#load into RStudio viewer (not required)
iris = iris

#summary at the group level
summary_grouped = iris %>% 
       group_by(Species) %>%
       summarize(mean_s_length = mean(Sepal.Length),
                 max_s_width = max(Sepal.Width))

#summary at the overall level
summary_overall = iris %>% 
  summarize(mean_s_length = mean(Sepal.Length),
            max_s_width = max(Sepal.Width)) %>%
  mutate(Species = "Overall")

#append results for report       
summary_table = rbind(summary_grouped, summary_overall)
Run Code Online (Sandbox Code Playgroud)

多次执行此操作非常繁琐。我有点想要:

summary_overall = iris %>% 
       group_by(Species, total = TRUE) %>%
       summarize(mean_s_length = mean(Sepal.Length),
                 max_s_width = max(Sepal.Width))
Run Code Online (Sandbox Code Playgroud)

仅供参考-如果您熟悉SAS,我正在寻找可通过proc中的类,方法或类型语句使用的相同类型的功能,这意味着让我可以控制汇总级别并在一个调用中获得多个级别。

任何帮助表示赞赏。我知道我可以创建自己的函数,但希望已经存在一些东西。我也希望坚持使用整洁的编程风格,尽管我对此并不感兴趣。

Moo*_*per 5

另一种选择:

library(tidyverse)  

iris %>% 
  mutate_at("Species", as.character) %>%
  list(group_by(.,Species), .) %>%
  map(~summarize(.,mean_s_length = mean(Sepal.Length),
                 max_s_width = max(Sepal.Width))) %>%
  bind_rows() %>%
  replace_na(list(Species="Overall"))
#> # A tibble: 4 x 3
#>   Species    mean_s_length max_s_width
#>   <chr>              <dbl>       <dbl>
#> 1 setosa              5.01         4.4
#> 2 versicolor          5.94         3.4
#> 3 virginica           6.59         3.8
#> 4 Overall             5.84         4.4
Run Code Online (Sandbox Code Playgroud)