Cannot get the demographic data at the block group level

Hello I tried to get the demographic data at the block group level but I only got the result for the first variable and NAs for other columns. Can you help me to figure it out?

# Load the library 
library(tidyverse)
library(readxl)
library(lubridate)
library(ggplot2)
library(stringr)
library(purrr)
library(httr)
library(jsonlite)
library(tidycensus)
library(tidyr)
library(furrr)
library(sf)
library(units)
api_key <- "94d96c1dfb04afe285d0db958f78ded8a4b197f7"

# Function to extract multiple data from Census API for a given block group geoid
get_data_from_fips <- function(fips) {
  # Extract state, county, and block group from the FIPS code
  state <- substr(fips, 1, 2)
  county <- substr(fips, 3, 5)
  tract <- substr(fips, 6, 11)
  block_group <- substr(fips, 12, 12)
  
  # Define the URL for the API request
  base_url <- "https://api.census.gov/data/2021/acs/acs5"
  variables <- paste0(
    "B19013_001E,", # Median household income 
    "B25010_001E,", # Median household size
    "B01003_001E,", # Total population
    "B01001_026E,", # Female population
    "B15003_001E,", # Educational attainment for the population 25 yrs and over
    "B15003_022E,", # Bachelor's degree population
    "B01002_001E,", # Median age by sex
    "B02001_001E,", # Race total
    "B02001_002E,", # White alone
    "B02001_003E,", # Black or African American alone
    "B02001_004E,", # American Indian and Alaska Native alone
    "B02001_005E,", # Asian alone
    "B02001_006E,", # Native Hawaiian and Other Pacific Islander alone
    "B02001_007E,", # Some other race alone
    "B02001_008E"   # Two or more races
  )
  
  url <- paste0(base_url, "?get=", variables, "&for=block%20group:", block_group, "&in=state:", state, "+county:", county, "+tract:", tract, "&key=", api_key)
  
  # Make the API request
  response <- GET(url)
  data <- fromJSON(content(response, as="text"))[[2]] # Fetching second element which contains the data
  
  
  # Create a named vector with all the extracted data
  extracted_data <- as.numeric(data[1:15]) # Ensure you convert the data to numeric
  names(extracted_data) <- c(
    "median_income", "median_household_size", "total_population", "female_population", 
    "education_25_over", "bachelor_degree_pop", "median_age", "race_total", 
    "white", "black_african_american", "american_indian_alaska_native", "asian",
    "native_hawaiian_pacific_islander", "other_race", "two_or_more_races"
  )
  
  return(extracted_data)
}

# Extract multiple data points for each block FIPS
test <- sample_fips |>
  mutate(data = purrr::map(.x = block_fips, .f = get_data_from_fips)) |>
  tidyr::unnest_wider(data)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.