我正在创建一堆基本状态报告,我发现乏味的一件事是向我的所有表添加总行。我目前正在使用 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,我正在寻找通过 proc 中的类、方式或类型语句提供的相同类型的功能,这意味着让我控制汇总级别并在一次调用中获得多个级别。
任何帮助表示赞赏。我知道我可以创建自己的函数,但希望有一些已经存在的东西。我也更愿意坚持 tidyverse 编程风格,尽管我并没有这样做。
最佳答案
另一种选择:
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
关于r - 汇总不同聚合级别的数据 - R 和 tidyverse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56709648/