【问题标题】:Summarise the output per group in dataframe R总结数据帧 R 中每组的输出
【发布时间】: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(),即... %&gt;% summarise(Avg_Age = mean(Age))

标签: r dplyr summary


【解决方案1】:

您想将mutate() 替换为summarize()。您也可以使用summarise() 作为别名。 mutate() 函数计算新值并创建新列以返回与原始行数相同的 data.frame。 summarize() 函数根据分组变量聚合数据,并创建新的汇总列。生成的 data.frame 只有行数作为分组变量的唯一组合,并且只有分组列加上新的聚合列。

data.frame(Sex, Age) %>%
  group_by(Sex) %>%
  summarize(Ave_age = mean(Age))
# A tibble: 2 x 2
  Sex    Ave_age
  <chr>    <dbl>
1 Female    21.3
2 Male      21.6

【讨论】:

  • 你要我删除我的答案吗?
  • 不,没关系:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
相关资源
最近更新 更多