我正在按年龄和年龄组分类每个县的病例数。所有年龄段,年龄和县的df和矢量示例:
library(tidyverse)
df <- data.frame(
"year" = c(2010, 2010, 2011, 2013, 2014, 2014,
2015, 2015, 2015, 2016),
"age_group" = c("20-39", "0-19", "0-19", "60-79",
"80-99", "20-39","20-39", "60-79",
"20-39", "80-99"),
"county" = c("a", "b", "b", "a", "c", "b", "b",
"a", "a", "a"))
all_age_groups <- c("0-19", "20-39", "40-59", "60-79", "80-99")
all_years <- c(2010:2017)
all_counties <- c("a", "b", "c", "d")
县“ a”,“ b”和“ c”缺少某些年龄段或年份。县“ d”缺少所有年龄段和年龄(无病例)。
这可以添加任何缺少的年龄段:
ex_func <- function(df_orig, selectcounty) {
df_age_group <- data.frame("age_group" = all_age_groups)
df2 <- df_orig %>%
filter(county == selectcounty) %>%
group_by(age_group, year) %>%
summarise(cases = n()) %>%
spread(year, cases) %>%
full_join(., df_age_group, by = "age_group") %>%
replace(is.na(.), 0) %>%
ungroup() %>%
mutate(age_group = factor(age_group, levels = all_age_groups)) %>%
arrange(age_group)
df2
}
但是,如果没有使用mutate
为每个缺少的年份手动创建一个新的年份,我将无法成功处理缺少的年份列。
我正在寻找一种方法,最好是在dplyr
中:
1)搜索all_years
中不存在的年份作为df中的列
2)为缺少的每一年添加一列
3)使每个新列的所有行等于0
4)在各列中维持年份(2010-2017)的顺序,在df $ age_group中保留年龄组
“ b”郡的预期结果的简短版本:
df2 <- ex_func(df, "b")
age_group `2010` `2011 `2012` `2013` `2014 `2015`
0-19 1 1 0 0 0 0
20-39 0 0 0 0 1 1
40-59 0 0 0 0 0 0
60-79 0 0 0 0 0 0
80-99 0 0 0 0 0 0