I'm pretty new to using API, and have had some success, but am running into challenges grabbing data from Table B19013 by zip code. This is the code I'm using.
# 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)
# Function to fetch B19013 data for all U.S. ZCTAs for the year 2022
get_b19013_data_us_2022 <- function() {
tryCatch({
data <- get_acs(geography = "zip code tabulation area",
year = 2022,
survey = "acs5",
table = "B19013",
output = "wide") %>%
mutate(Year = 2022)
return(data)
}, error = function(e) {
message("Error with year 2022: ", e$message)
return(NULL)
})
}
# Fetch the data for 2022
b19013_data_us_2022 <- get_b19013_data_us_2022()
# Check if the data frame is empty
if (is.null(b19013_data_us_2022)) {
message("No data retrieved for U.S. 2022.")
} else {
# Save the data to a CSV file on your desktop
write.csv(b19013_data_us_2022, "~/Desktop/B19013_Median_Income_US_2022.csv", row.names = FALSE)
}