我有1000个样本的数据。数据有20个变量(1个数值变量和19个分类变量)。在一个代码中,我想通过每个级别的分类变量来计算数值变量的平均值和SD。例如,我想知道按性别划分的数值变量的平均值。然后,同时,我要按年龄组、教育程度等定性变量计算这一平均值。
如果我使用group_by
(性别、年龄、学历、.),那么我就不能分别用每个等级的分类变量来计算数值变量的平均值。
如何用所有的范畴变量来计算数值变量的平均值?
发布于 2022-01-06 02:36:35
我没有做所有的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)
https://stackoverflow.com/questions/70586586
复制相似问题