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

Getting summary by group and overall using 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_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

稍微改变一下也可以做到。

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

如果您有一个变量可以作为总结依据,这些答案就很棒。两个呢?我想对一个进行总结,但将另一个保持原样。上面的解决方案在这种情况下不起作用,因为数据框仍然需要分组。

#Data set up 
set.seed(3243242)
dsn <- tibble(
  obese = sample(c(TRUE, FALSE), size=100, replace = TRUE),
  sex = sample(c("M", "F"), size=100, replace=TRUE),
                  age = rnorm(n=100, mean=20 + 4*(sex=="F"), sd=0.1)
                    )
library("tidyverse")

我使用 2 group_by 个变量重述了原来的问题。

#Extend to 2 group_by variables?
df1 <- dsn %>%
  group_by(sex, obese) %>% 
  summarise(mean_age = mean(age)) %>%
  ungroup() 

#Also across sex
df2 <- dsn %>%
  group_by(obese) %>% 
  summarise(mean_age = mean(age)) %>%
  ungroup() 

#Final_result:
bind_rows(df1, df2)

一步完成的方法?您可以使用 add_row() 添加 mean 但不能使用分组 df。另一种选择是创建一个函数来完成组数据集上的所有事情。如果您还想做其他事情,比如排序或创建新变量,您可以在函数中完成。然后,您可以将该函数应用于每个分组数据集。通过 dplyr::bind_rows() 组合后,可以通过 tidyr::replace_na().

将缺少的组变量更改为全部
  #'@param df_group A grouped tibble
find_summary <- function(df_group){
  df_group %>% 
summarize(mean_age = mean(age))  #add other dplyr verbs here as needed like arrange or mutate
}

bind_rows(
    find_summary(group_by(dsn, sex, obese)),
    find_summary(group_by(dsn, obese))
    ) %>%
     replace_na(list(sex = "all"))
sex   obese mean_age
  <chr> <lgl>    <dbl>
1 F     FALSE     24.0
2 F     TRUE      24.0
3 M     FALSE     20.0
4 M     TRUE      20.0
5 all   FALSE     21.7
6 all   TRUE      22.3

如果你想要所有变量的汇总,一个变量,两个变量,你可以扩展这个想法。

bind_rows(
    find_summary(group_by(dsn, sex, obese)),
    find_summary(group_by(dsn, obese)),
    find_summary(dsn)
    ) %>%
     replace_na(list(sex = "all", obese = "all"))
  sex   obese mean_age
  <chr> <chr>    <dbl>
1 F     FALSE     24.0
2 F     TRUE      24.0
3 M     FALSE     20.0
4 M     TRUE      20.0
5 all   FALSE     21.7
6 all   TRUE      22.3
7 all   all       22.0