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 }