首页 > 解决方案 > 在 dplyr 中计算分组数据的条件摘要

问题描述

我有一个人口死亡率数据集,按年份、剥夺的十分位(排名)、性别、死因和年龄划分。年龄数据分为 0-1、1-4、5-9、10-14 等类别。

我试图强制我的数据集,以便将 0-1 和 1-4 的死亡率数据合并在一起以创建年龄类别 0-4、5-9、10-14 等等,直到 90 岁。我的数据很长格式。

使用 dplyr 我正在尝试使用 if_else 和 summarise() 将 0-1 和 1-4 的死亡率数据汇总在一起,但是我应用的任何代码迭代都只是产生了我最初拥有的相同数据集,即代码没有合并我的数据在一起。

head(death_popn_long) #cause_death variable content removed for brevity

Year deprivation_decile  Sex cause_death ageband deaths popn
1 2017                  1 Male          NA       0      0 2106
2 2017                  1 Male          NA       0      0 2106
3 2017                  1 Male          NA       0      0 2106
4 2017                  1 Male          NA       0      0 2106
5 2017                  1 Male          NA       0      0 2106
6 2017                  1 Male          NA       0      0 2106

#Attempt to merge ageband 0-1 & 1-4 by summarising combined death counts

test <- death_popn_long %>% 
group_by(Year, deprivation_decile, Sex, cause_death, ageband) %>%
summarise(deaths = if_else(ageband %in% c("0", "1"), sum(deaths), 
deaths))

我希望死亡变量是这些年龄段的死亡人数的组合(即 0-1 和 1-4 的总和),但是上面我尝试的任何替代代码都只是重新创建了我已经拥有的先前数据集。

标签: r

解决方案


如果你打算操纵它的组,你不想ageband在你的声明中使用。group_by您需要创建新版本,ageband然后按以下方式分组:

test <- death_popn_long %>% 
    mutate(new_ageband = if_else(ageband %in% c("0", "1"), 1, ageband)) %>%
    group_by(Year, deprivation_decile, Sex, cause_death, new_ageband) %>%
    summarise(deaths = sum(deaths))

如果你想要一个稍微短一点的版本,你可以new_agebandgroup_by子句中定义而不是事先使用mutate动词。我这样做是为了明确。

此外,对于未来的 SO 问题 - 在您的问题中提供数据非常有帮助(使用类似的东西dput)。:)


推荐阅读