r - 使用 tidyverse 按组和整体获取摘要

标签 r dplyr tidyverse mean summarize

我正在尝试找到一种方法来使用 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

关于r - 使用 tidyverse 按组和整体获取摘要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60437783/

相关文章:

正则表达式提取美国邮政编码但不提取伪代码

r - 将数据框中的所有列相互相乘的有效方法

r - 如何在facet_grid中指定列或如何更改facet_wrap中的标签

r - Dplyr:过滤系列中日期的最后一个条目

python - Pandas DataFrame to Reticulate 结果出现 IndexError

使用 ggplot2 绘制来自 Geotiff 的 R 背景图

r - 在 group_by 之后连接表

r - 将字符串参数作为 dplyr 中的数据框列名称传递给函数

r - 基于连续行值创建新的数据框

r - 如何使用 tidyr 自动创建变量?