【发布时间】:2020-09-02 17:07:32
【问题描述】:
(学生考试,请勿回复;))
大家好,
我对 R 有点陌生,但我找不到解决问题的方法。
我的数据框中有两列:性别和年龄。我想知道每个性别的平均年龄。
我希望这个答案是 2 x 2 表。
我尝试了什么:
我可以找到两组的平均值,但 R 将它们作为列添加到我的数据框中。
另外,我知道如何用我想要的结果制作一个表格,但这当然不是原始数据集。
我想要的是一张 2x2 的表格:
Sex AVG_age
男 21.2
女 21.5
在我的代码下面:
library(dplyr)
set.seed(13)
Sex <- sample(c("Male","Female"), 100, replace=TRUE, prob = c(0.53, 0.47))
Age <- sample((18:25),100,replace=T)
# Output with extra column
df_sex_age <- data.frame(Sex,Age) %>%
group_by(Sex) %>%
mutate(Avg_Age = mean(Age))
View(df_sex_age)
# What I want
data.frame(Sex = c("Male", "Female"),
Avg_Age = c(21.2, 21.5))
【问题讨论】:
-
只需将
mutate()替换为summarise(),即... %>% summarise(Avg_Age = mean(Age))