Problems Fetching 5-Year Zip-Level Data w API

Hi All,

I've been successfully fetching ACS 5-year state legislative district data using my API key for years 2010 - 2022.

However, I am having issues fetching the same data at the zip-level (for years 2011 - 2022). I am able to fetch zip-level data for years 2011 - 2018, but when I try to add 2019 - 2022, I receive an error that says my API key is invalid. 

Below is the code that doesn't work for 2011 - 2022.

Thanks for any help!

# Install required packages
if (!require(tidycensus)) install.packages("tidycensus")
if (!require(dplyr)) install.packages("dplyr")

# Load the packages
library(tidycensus)
library(dplyr)

# Set your Census API key
census_api_key("your_api_key", install = TRUE, overwrite = TRUE)

# Define the years you're interested in (2011 to 2022)
years <- 2011:2022
states <- c("CO", "AZ", "ID", "MT", "NV", "NM", "UT", "WY")

# Function to fetch population data for a specific year and state
get_population_data <- function(year, state) {
tryCatch({
data <- get_acs(geography = "zip code tabulation area",
state = state,
year = year,
survey = "acs5",
table = "B01003",
output = "wide") %>%
mutate(Year = year, State = state)
return(data)
}, error = function(e) {
message("Error with year ", year, ", state ", state, ": ", e$message)
return(NULL)
})
}

# Initialize an empty list to store the data
all_data <- list()

# Loop over each year and state, fetching data
for (state in states) {
for (year in years) {
data <- get_population_data(year, state)
if (!is.null(data)) {
all_data[[paste(state, year)]] <- data
}
}
}

# Combine the data from different years and states
combined_data <- bind_rows(all_data)

Parents
  • ZCTAs don't nest within states, so it's not (currently) possible to request ZCTA data by state. You'd have to get all ZCTAs in the U.S. (They changed this up a few years ago, and for a time, it was possible to request ZCTAs by state, but that changed recently, I think with the 2021 5-year ACS, and it's once again not an option. I don't know if or when that might change.)

Reply
  • ZCTAs don't nest within states, so it's not (currently) possible to request ZCTA data by state. You'd have to get all ZCTAs in the U.S. (They changed this up a few years ago, and for a time, it was possible to request ZCTAs by state, but that changed recently, I think with the 2021 5-year ACS, and it's once again not an option. I don't know if or when that might change.)

Children