【问题标题】:Getting summary by group and overall using tidyverse使用 tidyverse 按组和整体获取摘要
【发布时间】:2020-06-11 17:38:21
【问题描述】:

我正在尝试找到一种方法来使用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 的类似功能在更短的时间内完成 任何帮助将不胜感激

【问题讨论】:

标签: r dplyr tidyverse mean summarize


【解决方案1】:

一个选项可能是:

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

【讨论】:

    【解决方案2】:

    稍微切换一下也可以。

    final_result <- dsn %>% 
      add_row(sex = "All", age = mean(age)) %>% 
      group_by(sex) %>% 
      summarise(mean_age = mean(age))
    

    【讨论】:

    • 我们发布了几乎相同的内容 :) 但是,有一个实质性的区别:如果年龄不在全球环境中,您的解决方案将不起作用。
    • 谢谢@vanao veneri。我稍微修改了代码,它工作了
    猜你喜欢
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 2021-08-02
    • 2014-08-18
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多