Skip to content

Instantly share code, notes, and snippets.

@benjamin-chan
Last active May 29, 2025 19:04
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 = 2023) {
require(magrittr)
require(dplyr)
require(tidyr)
require(tidycensus)
labels <-
load_variables(year, dataset = dataset, cache = TRUE) %>%
mutate(label = gsub(":$", "", label)) %>%
separate_wider_delim(label, names_sep = "", delim = "!!", too_few = "align_start") %>%
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:
# > zcta <- c("08701", "92336", "90650")
# > getACSbyZCTA(zcta, variables = "DP05_0001E")
# > df <- getACSbyZCTA(zcta, table = "DP02")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment