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 packagesif (!require(tidycensus)) install.packages("tidycensus")if (!require(dplyr)) install.packages("dplyr")
# Load the packageslibrary(tidycensus)library(dplyr)
# Set your Census API keycensus_api_key("your_api_key", install = TRUE, overwrite = TRUE)
# Define the years you're interested in (2011 to 2022)years <- 2011:2022states <- c("CO", "AZ", "ID", "MT", "NV", "NM", "UT", "WY")
# Function to fetch population data for a specific year and stateget_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 dataall_data <- list()
# Loop over each year and state, fetching datafor (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 statescombined_data <- bind_rows(all_data)
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 …
Separately, for larger tables I am gathering, does anyone have advice on how to pull the specific variables I want rather than pulling the entire table?