分组汇总,整体使用tidyverse [英] Getting summary by group and overall using tidyverse
本文介绍了分组汇总,整体使用tidyverse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试找到一种方法,使用dplyr
#Data set-up
sex <- sample(c("M", "F"), size=100, replace=TRUE)
age <- rnorm(n=100, mean=20 + 4*(sex=="F"), sd=0.1)
dsn <- data.frame(sex, age)
library("tidyverse")
#Using dplyr to get means by group and overall
mean_by_sex <- dsn %>%
group_by(sex) %>%
summarise(mean_age = mean(age))
mean_all <- dsn %>%
summarise(mean_age = mean(age)) %>%
add_column(sex = "All")
#combining the results by groups and overall
final_result <- rbind(mean_by_sex, mean_all)
final_result
#> # A tibble: 3 x 2
#> sex mean_age
#> <fct> <dbl>
#> 1 F 24.0
#> 2 M 20.0
#> 3 All 21.9
#This is the table I want but I wonder if is the only way to do this
有没有办法使用group_by_at
或group_by_all
或使用tidyverse和dplyr
的类似函数来缩短步骤
如有任何帮助,我们将不胜感激
推荐答案
一个选项可能是:
dsn %>%
group_by(sex) %>%
summarise(mean_age = mean(age)) %>%
add_row(sex = "ALL", mean_age = mean(dsn$age))
sex mean_age
<fct> <dbl>
1 F 24.0
2 M 20.0
3 ALL 21.9
这篇关于分组汇总,整体使用tidyverse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文