0

I am using the WHO dataset in R and currently having trouble collapsing the age section into five groups as seen in this picture.

enter image description here

I have pasted a copy of my code below, anything helps.

names(who) <- str_replace(names(who), "newrel", "new_rel")
who2 <- who %>%
  gather("codes", "case", 5:60) %>%
  select(-iso2, -iso3) %>%
  separate(codes, c("new", "type", "sexage"), sep = "_") %>%
  select(-new) %>%
  separate(sexage, into = c("sex", "age"), sep = 1,convert=TRUE)


who2 %>% 

    filter(!is.na(case)) %>% 

    group_by(year, sex, age) %>% 

    mutate(cases = sum(case)) %>%

  mutate(age = factor(age, levels=c("14","1524", "2534","3544","4554","5564","65"),ordered=TRUE)) %>% mutate(age = fct_recode(age, "0-14" = "14", "15-24" = "1524", "25-34" = "2534", "35-44" = "3544", "45-54" = "4554", "55-64" = "5564", "65+" = "65")) %>% 

ggplot() + 

  geom_line(mapping = aes(x = year, y = cases, color = age)) + 

facet_wrap(~sex)
Lilguyuno
  • 5
  • 4
  • Could you provide a reproducible example of the data? I see that you're following R for Data Science, so maybe there's a missing step – csgroen Apr 16 '21 at 09:40
  • The data is from R. I initially transferred the data like so: names(who) <- str_replace(names(who), "newrel", "new_rel")#newline who2 <- who – Lilguyuno Apr 16 '21 at 10:09
  • I think you need to specify `group = age` within `aes()`. Not sure if that is the only issue. – TimTeaFan Apr 16 '21 at 10:34
  • OP, you need to share the entire code for how you converted `who` to `who2`. You've given us only one of the lines. – chemdork123 Apr 17 '21 at 15:16
  • Thiis is the rest of the code: names(who) <- str_replace(names(who), "newrel", "new_rel") who2 <- who %>% gather("codes", "case", 5:60) %>% select(-iso2, -iso3) %>% separate(codes, c("new", "type", "sexage"), sep = "_") %>% select(-new) %>% separate(sexage, into = c("sex", "age"), sep = 1,convert=TRUE) – Lilguyuno Apr 18 '21 at 04:27
  • Does this answer your question? [Create categorical variable in R based on range](https://stackoverflow.com/questions/2647639/create-categorical-variable-in-r-based-on-range) – tjebo Apr 18 '21 at 08:59
  • and https://stackoverflow.com/questions/5570293/add-column-which-contains-binned-values-of-an-integer-column and https://stackoverflow.com/questions/6104836/splitting-a-continuous-variable-into-equal-sized-groups - check all linked threads, there are plenty. If this still doesn't help, please edit your question and tell us why not. – tjebo Apr 18 '21 at 09:01

0 Answers0