Using mutate and filter

I am trying to sort my data into multiple columns, based on other column values.

The code I am using to get one group is:
df_grouped <- df %>%
group_by(region) %>%
filter(age > 10, age < 15) %>%
summarise(population10-15 = sum(population))

What I want is to get multiple groups:
df_grouped <- df %>%
group_by(region) %>%
mutate(population1 = filter(age > 0, age < 5)) %>%
mutate(population2 = filter(age >= 5, age < 10)) %>%
mutate(population3 = filter(age > =10, age < 15)) %>%
summarise(population = sum(population))

Hope this makes sense, my DF is a list of multiple regions with age (0-55) and population(total number)
ie
region age population
a - 1 - 183
a - 2 - 218
b - 1 - 153
b - 2 - 128
c - 1 - 67
c - 2 - 35
(but 500 regions and age going from 0-55)

I also tried case_when, but couldn't get this to work.

Thanks,
Ben

Might be helpful to show an example of what you'd like to get given the data set you describe.

Something like this would do I think:

n <- 500
X <- dplyr::tibble(
  age = sample(60, n, replace = TRUE),
  region = sample(LETTERS[1:5], n, replace = TRUE),
  population = sample(20, n, replace = TRUE)
)
breaks <- c(seq(0,80, by = 5))
labels <- paste("population", seq_len(length(breaks) - 1))

X %>% 
  dplyr::mutate(bracket = cut(age, breaks = breaks, labels = labels, right=TRUE)) %>% 
  dplyr::group_by(bracket, region) %>% 
  dplyr::summarise(population = sum(population)) %>% 
  tidyr::pivot_wider(names_from="bracket", values_from="population", values_fill = 0)
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Thanks, I do need to think about this further, this is my first week of R, and I am still figuring a lot out.

What I was thinking was:
group - age group - population
a - (0-5) - 450
a - (5-10) - 389
a- (10-15) - 482
b - (0-5) - 217
b - (5-10) - 624
b - (10-15) - 537

But thinking about this more, I am thinking:
group - pop0-5 - pop(5-10 - pop (10-15
a - 450 - 389 - 482
b - 217 - 624 - 537

Regards,
Ben