r - 在 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 的总和),但是上面我尝试的任何替代代码都只是重新创建了我已经拥有的先前数据集。
解决方案
如果你打算操纵它的组,你不想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_ageband
在group_by
子句中定义而不是事先使用mutate
动词。我这样做是为了明确。
此外,对于未来的 SO 问题 - 在您的问题中提供数据非常有帮助(使用类似的东西dput
)。:)
推荐阅读
- javascript - 如何使用 JavaScript 检查另一个元素中是否有一个元素
- java - 无法解析intellij中的符号jsonobject
- python - 图形大小随颜色条变化
- python - 在pygame中单击图像时如何运行函数?
- android-studio - 我不知道我的代码有什么问题
- kotlin - 发送不和谐心跳后客户端关闭连接,而不和谐响应 4002 错误代码
- angular - mat-date-range-picker 的角度材质自定义输入
- c++ - 等待线程完成而不冻结 MFC 中的 UI
- javascript - ExportButton 的资源属性不起作用(react-admin 3.7.1)
- html - 如何在 html 中显示“<--”,以便破折号位于“大于”符号的曲线中间?