Skip to content

Instantly share code, notes, and snippets.

@benjamin-chan
Last active June 24, 2024 21:40
Show Gist options
  • Save benjamin-chan/bc807e5b4f431fdb5e70d85f9fdeac90 to your computer and use it in GitHub Desktop.
Save benjamin-chan/bc807e5b4f431fdb5e70d85f9fdeac90 to your computer and use it in GitHub Desktop.
Grab ACS 5-year data (2017-2021) via API
# US Census ACS 5-year API documentation: https://www.census.gov/data/developers/data-sets/acs-5year.html
# tidycensus documentation: https://walker-data.com/tidycensus/
Sys.getenv("CENSUS_API_KEY") # load pre-installed Census API key
getACSbyZCTA <- function(lookup, table = NULL, variables = NULL, dataset = "acs5/profile", year = 2022) {
require(magrittr)
require(dplyr)
require(tidyr)
require(tidycensus)
labels <-
load_variables(year, dataset = dataset, cache = TRUE) %>%
mutate(label = gsub(":$", "", label)) %>%
separate(label, sprintf("label%d", 1:6), sep = ":?!!", extra = "drop", fill = "right") %>%
rename(variable = name)
get_acs(geography = "zcta", table = table, year = year, variables = variables) %>%
rename(zipcode = GEOID) %>%
filter(zipcode %in% lookup) %>%
inner_join(labels) %>%
arrange(zipcode, variable) %>%
select(-c(NAME, moe))
}
# Example calls:
# > getACSbyZCTA(table = "DP02")
# > getACSbyZCTA(variables = "DP05_0001E")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment