From 4ea0583d3a03e042fe7f36773a91e9da0d5908da Mon Sep 17 00:00:00 2001 From: Jared Knowles Date: Wed, 29 Apr 2026 16:36:22 -0400 Subject: [PATCH] feat(per-capita): use per-year F-33 population in spending verbs cog_spending(per_capita = TRUE) and cog_revenue(per_capita = TRUE) now divide each year's amount by that gov-year's population from gov_population_yearly (drawn from long.population) instead of a single static ACS 2018-2022 value. Adds pop_source column with values 'census_f33' or 'unavailable'. --- R/spending.R | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/R/spending.R b/R/spending.R index 0c452ca..e8bd7dd 100644 --- a/R/spending.R +++ b/R/spending.R @@ -143,18 +143,24 @@ cog_spending <- function(govid, years, category = NULL, .attach_per_capita <- function(result, con, govid) { if (nrow(result) == 0L) { result$amt_per_capita_nominal <- numeric(0) + result$pop_source <- character(0) return(result) } + years_lit <- paste(unique(as.integer(result$year)), collapse = ",") sql <- sprintf( - "SELECT canonical_govid, population_acs - FROM canonical_fips_xwalk - WHERE canonical_govid IN (%s)", - .sql_lit_chr(govid) + "SELECT canonical_govid, year, population + FROM gov_population_yearly + WHERE canonical_govid IN (%s) + AND year IN (%s)", + .sql_lit_chr(govid), years_lit ) pops <- tibble::as_tibble(DBI::dbGetQuery(con, sql)) - result <- dplyr::left_join(result, pops, by = "canonical_govid") - result$amt_per_capita_nominal <- result$amt_nominal / result$population_acs - result$population_acs <- NULL + result <- dplyr::left_join(result, pops, + by = c("canonical_govid", "year")) + result$amt_per_capita_nominal <- result$amt_nominal / result$population + result$pop_source <- ifelse(is.na(result$population), + "unavailable", "census_f33") + result$population <- NULL result }