我有一个人口死亡率数据集,按年份、十进制(排名)、性别、死因和年龄分类。年龄数据分为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的总和),但是上面的任何替代代码都只是重新创建了我已经拥有的以前的数据集。
发布于 2019-06-04 05:59:25
如果您打算操作其组,则不希望在group_by
语句中使用ageband
。您需要创建新版本的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))
如果您想要一个稍微短一点的版本,您可以在group_by
子句中定义new_ageband
,而不是事先使用mutate
动词。我这么做只是为了表达清楚。
另外,对于将来的SO问题-在你的问题中提供数据(使用dput
之类的东西)是非常有用的。:)
https://stackoverflow.com/questions/56434683
复制相似问题