如何按年月计算指定列总和?R语言新冠病例数据处理问询
按年月统计指定年龄组病例总数的解决方法
需求
按年月统计AgeGroup_20_to_24列的病例总和,即计算每个年月(如01/2020、02/2020)对应的该年龄组病例总数。
原代码存在的问题
你写的代码无法得到预期结果,原因如下:
- 仅按
year分组,未包含month,无法实现按「年月」维度聚合 - 使用
mutate(total = sum(AgeGroup_20_to_24))计算的是整列的总和,而非分组后的组内总和,应该用summarize替代mutate - 操作顺序错误:应先分组再进行聚合计算,而非先计算总和再分组
示例数据结构
structure(list(Date = c("3/9/2020", "3/10/2020", "3/11/2020", "3/12/2020", "3/13/2020", "3/14/2020"), AgeGroup_0_to_19 = c(1, 0, 2, 0, 0, 2), AgeGroup_20_to_24 = c(1, 0, 2, 0, 2, 1), AgeGroup_25_to_29 = c(1, 0, 1, 2, 2, 2), AgeGroup_30_to_34 = c(0, 0, 2, 3, 4, 3), AgeGroup_35_to_39 = c(3, 1, 2, 1, 2, 1), AgeGroup_40_to_44 = c(1, 2, 1, 3, 3, 1), AgeGroup_45_to_49 = c(1, 0, 0, 2, 0, 1), AgeGroup_50_to_54 = c(2, 1, 1, 1, 0, 1), AgeGroup_55_to_59 = c(1, 0, 1, 1, 1, 2), AgeGroup_60_to_64 = c(0, 2, 2, 1, 1, 3), AgeGroup_70_plus = c(2, 0, 2, 0, 0, 0)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
正确实现代码
library(dplyr) library(lubridate) xAge20To24 <- covid %>% # 转换日期格式并提取年、月 mutate(dates = mdy(Date), year = year(dates), month = month(dates)) %>% # 按年和月组合分组 group_by(year, month) %>% # 计算每个年月的AgeGroup_20_to_24病例总和 summarize(total_20_to_24 = sum(AgeGroup_20_to_24)) %>% # 可选:生成mm/yyyy格式的年月字符串,便于查看 mutate(year_month = paste0(month, "/", year)) %>% # 调整列顺序,优化显示 select(year_month, year, month, total_20_to_24) View(xAge20To24)
代码说明
- 日期处理:用
lubridate包的mdy函数将字符串格式的日期转换为标准日期类型,再提取年份和月份; - 分组聚合:通过
group_by(year, month)按「年+月」分组,确保每个年月为独立的统计单元; - 计算总和:
summarize函数会对每个分组计算AgeGroup_20_to_24的总和,最终输出每组一行的聚合结果; - 优化显示:可选的
mutate(year_month = ...)步骤生成直观的年月格式字符串,方便快速查看统计结果。
用你提供的示例数据运行代码后,会得到3/2020对应的total_20_to_24为6(1+0+2+0+2+1)。
内容的提问来源于stack exchange,提问作者Jase C
相关产品推荐
相关产品推荐

