Last active
June 24, 2024 21:40
-
-
Save benjamin-chan/bc807e5b4f431fdb5e70d85f9fdeac90 to your computer and use it in GitHub Desktop.
Grab ACS 5-year data (2017-2021) via API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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