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

10-12 20:20