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

Summarize data at different aggregate levels - R and 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)

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

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

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

感谢任何帮助。我知道我可以创建自己的函数,但希望已经存在一些东西。我也更愿意坚持使用 tidyverse 编程风格,尽管我不喜欢那样。

library(dplyr)

iris %>% 
  group_by(Species) %>%
  summarize(mean_s_length = mean(Sepal.Length),
            max_s_width = max(Sepal.Width)) %>%
  ungroup() %>% 
  mutate_at(vars(Species), as.character) %>% 
  {rbind(.,c("Overal",mean(.$mean_s_length),max(.$max_s_width)))} %>%
  mutate_at(vars(-Species), as.double) %>% 
  mutate_at(vars(Species), as.factor)
#> # A tibble: 4 x 3
#>   Species    mean_s_length max_s_width
#>   <fct>              <dbl>       <dbl>
#> 1 setosa              5.01         4.4
#> 2 versicolor          5.94         3.4
#> 3 virginica           6.59         3.8
#> 4 Overal              5.84         4.4

reprex package (v0.3.0)

于 2019-06-21 创建

一种方法,也很乏味但在一个较长的管道中,是将第二个汇总指令放在 bind_rows.
as.character 调用避免了警告:

Warning messages:
1: In bind_rows_(x, .id) :
binding factor and character vector, coercing into character vector
2: In bind_rows_(x, .id) :
binding character and factor vector, coercing into character vector

library(tidyverse)

summary_grouped <- iris %>% 
  mutate(Species = as.character(Species)) %>%
  group_by(Species) %>%
  summarize(mean_s_length = mean(Sepal.Length),
            max_s_width = max(Sepal.Width)) %>%
  bind_rows(iris %>% 
              summarize(mean_s_length = mean(Sepal.Length),
                        max_s_width = max(Sepal.Width)) %>%
              mutate(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

也许是这样的:

由于要对同一个输入执行不同的操作(iris),最好map对不同的汇总函数应用到数据上。 map_dfr 使用 bind_rows

组合列表输出
library(dplyr)
library(purrr)

pipe <- . %>%
  group_by(Species) %>%
  summarize(
    mean_s_length = mean(Sepal.Length),
    max_s_width   = max(Sepal.Width))

map_dfr(
  list(pipe, . %>% mutate(Species = "Overall") %>% pipe),
  exec, 
  iris)
#> Warning in bind_rows_(x, .id): binding factor and character vector,
#> coercing into character vector
#> Warning in bind_rows_(x, .id): binding character and factor vector,
#> coercing into character vector
#> # 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

只需要在双数据集上应用所需函数一次的解决方案:

library(tidyverse)
iris %>%
  rbind(mutate(., Species = "Overall")) %>%
  group_by(Species) %>%
  summarize(
    mean_s_length = mean(Sepal.Length),
    max_s_width = max(Sepal.Width)
  )

# A tibble: 4 x 3
  Species    mean_s_length max_s_width
  <chr>              <dbl>       <dbl>
1 Overall             5.84         4.4
2 setosa              5.01         4.4
3 versicolor          5.94         3.4
4 virginica           6.59         3.8

技巧是使用新组 ID 传递原始数据集(即 Species):mutate(iris, Species = "Overall")

您可以编写一个函数,在 ungrouped tibble 上执行相同的 summarize,并将其绑定到最后。

summarize2 <- function(df, ...){
 bind_rows(summarise(df, ...), summarize(ungroup(df), ...))
}

iris %>% 
  group_by(Species) %>%
  summarize2(
    mean_s_length = mean(Sepal.Length),
    max_s_width = max(Sepal.Width)
  )

# # A tibble: 4 x 3
#   Species    mean_s_length max_s_width
#   <fct>              <dbl>       <dbl>
# 1 setosa              5.01         4.4
# 2 versicolor          5.94         3.4
# 3 virginica           6.59         3.8
# 4 NA                  5.84         4.4

如果需要,您可以为 "Overall" 组的命名添加一些逻辑

summarize2 <- function(df, ...){
  s1 <- summarise(df, ...)
  s2 <- summarize(ungroup(df), ...)
  for(v in group_vars(s1)){
    if(is.factor(s1[[v]]))
      s1[[v]] <- as.character(s1[[v]])
    if(is.character(s1[[v]])) 
     s2[[v]] <- 'Overall'
    else if(is.numeric(s1[[v]])) 
     s2[[v]] <- -Inf
  }
  bind_rows(s1, s2)
}


iris %>% 
  group_by(Species, g = Petal.Length %/% 1) %>%
  summarize2(
    mean_s_length = mean(Sepal.Length),
    max_s_width = max(Sepal.Width)
  )

# # Groups:   Species [4]
#   Species        g mean_s_length max_s_width
#   <chr>      <dbl>         <dbl>       <dbl>
# 1 setosa         1          5.01         4.4
# 2 versicolor     3          5.35         2.9
# 3 versicolor     4          6.09         3.4
# 4 versicolor     5          6.35         3  
# 5 virginica      4          5.85         3  
# 6 virginica      5          6.44         3.4
# 7 virginica      6          7.43         3.8
# 8 Overall     -Inf          5.84         4.4

另一种选择:

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