【问题标题】:summarize more than one variables by multiple factors separately in R在R中分别通过多个因素汇总多个变量
【发布时间】:2022-01-05 00:33:33
【问题描述】:

我有样本大小为 1000 的数据。数据有 20 个变量(1 个数值变量和 19 个分类变量)。在一个代码中,我想通过每个级别的分类变量来计算数值变量的平均值和 SD。例如,我想知道按性别划分的数值变量的平均值。然后同时,我想按年龄组、教育程度和其他定性变量计算这个平均值。

如果我使用group_by(性别,年龄,教育,...),那么我不能分别计算每个级别的分类变量的数值变量的平均值。

如何计算所有分类变量的数值变量的平均值?

【问题讨论】:

标签: dplyr group-by tidyverse tidyr summarization


【解决方案1】:

我没有做所有 20 个变量,但我想这样的事情应该足够了。我不知道您所说的“一个代码”是什么意思,但这可以在 .rmd 的一大块中完成。

library(tidyverse)

studyid <- 1:1000
numeric <- sample(1:25, 1000, replace=TRUE)
color <- sample(c("red","blue","yellow"), 1000, replace=TRUE)
gender <- sample(c("male", "female"), 1000, replace=TRUE)
age <- sample(c("old","older","oldest"), 1000, replace=TRUE)

df <- data.frame(studyid, numeric, color, gender, age)

df %>%
  select(numeric, color) %>%
  group_by(color) %>%
  summarize(
    count = n(), 
    mean = mean(numeric, na.rm = TRUE),
    sd = sd(numeric, na.rm = TRUE)
  )
#> # A tibble: 3 × 4
#>   color  count  mean    sd
#>   <chr>  <int> <dbl> <dbl>
#> 1 blue     342  12.8  7.31
#> 2 red      324  12.9  6.86
#> 3 yellow   334  13.4  7.32

df %>%
  select(numeric, gender) %>%
  group_by(gender) %>%
  summarize(
    count = n(), 
    mean = mean(numeric, na.rm = TRUE),
    sd = sd(numeric, na.rm = TRUE)
  )
#> # A tibble: 2 × 4
#>   gender count  mean    sd
#>   <chr>  <int> <dbl> <dbl>
#> 1 female   485  13.0  7.25
#> 2 male     515  13.0  7.09

df %>%
  select(numeric, age) %>%
  group_by(age) %>%
  summarize(
    count = n(), 
    mean = mean(numeric, na.rm = TRUE),
    sd = sd(numeric, na.rm = TRUE)
  )
#> # A tibble: 3 × 4
#>   age    count  mean    sd
#>   <chr>  <int> <dbl> <dbl>
#> 1 old      330  12.0  6.95
#> 2 older    347  12.9  7.12
#> 3 oldest   323  14.2  7.27
Created on 2022-01-05 by the reprex package (v2.0.1)

【讨论】:

  • 您能否编写代码只使用一个 group_by 来获取不同类别的质量变量 x1、x2 和 x3 的平均年龄?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 2015-10-04
  • 2023-01-12
  • 2023-01-24
  • 1970-01-01
相关资源
最近更新 更多