How to aggregate or sum data in a dataset?

I have a dataset on population in states in the US from 2007-2019. However, it´s divided into age groups. I want to sum or aggregate the total population in the respective age groups so that I get one observation of the population for each state, each year.

Is there an easy way to do this?

structure(list(year = c("2007", "2007", "2007", "2007", "2007", 
"2007"), GEOID = c("01", "01", "01", "01", "01", "01"), NAME = c("Alabama", 
"Alabama", "Alabama", "Alabama", "Alabama", "Alabama"), variable = c("B01001_011", 
"B01001_012", "B01001_013", "B01001_014", "B01001_015", "B01001_016"
), estimate = c(150937, 138364, 152306, 161670, 166578, 157116
), moe = c(2782, 2515, 5403, 5542, 2135, 2196)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

Is this the sort of thing you want to do?

library(dplyr)
DF <- structure(list(year = c("2007", "2007", "2007", "2007", "2007", "2007"), 
                     GEOID = c("01", "01", "01", "01", "01", "01"), 
                     NAME = c("Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Alabama"), 
                     variable = c("B01001_011", "B01001_012", "B01001_013", "B01001_014", "B01001_015", "B01001_016"), 
                     estimate = c(150937, 138364, 152306, 161670, 166578, 157116), 
                     moe = c(2782, 2515, 5403, 5542, 2135, 2196)), row.names = c(NA, -6L), 
                class = c("tbl_df", "tbl", "data.frame"))
SUMS <- DF |> group_by(NAME,year) |> summarize(Total_pop=sum(estimate))
#> `summarise()` has grouped output by 'NAME'. You can override using the `.groups` argument.
SUMS
#> # A tibble: 1 x 3
#> # Groups:   NAME [1]
#>   NAME    year  Total_pop
#>   <chr>   <chr>     <dbl>
#> 1 Alabama 2007     926971

Created on 2022-03-30 by the reprex package (v2.0.1)

1 Like

Very much so! Thank you very much!

This topic was automatically closed 7 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.