0

Hello I have a problem extracting the census data from the block group in R. I have a bunch of specific addresses and I need to get the block group from these addresses and then extract corresponding census data, say the percentage of white/black/asian/hispanic/two races/other based on the block group. My code does not work out . Can you help me with it? Really appreciate it.

library(httr)
library(tidycensus)
library(purrr)

get_geocode_data <- function(address) {
  # The URL for the geocoding request
  url <- "https://geocoding.geo.census.gov/geocoder/geographies/onelineaddress"

  # The parameters for the request
  params <- list(
    address = address,
    format = "json",
    benchmark = "Public_AR_Current",
    vintage = "Current_Current"
  )

  # Make the request
  response <- GET(url, query = params)

  # Parse the response
  content <- content(response, "parsed", "application/json")

  # Extract the geographies data if it exists
  if (length(content$result$addressMatches) > 0) {
    geographies <- content$result$addressMatches[[1]]$geographies
  } else {
    geographies <- NULL
  }

  return(geographies)
}

addresses <- c(
  "Administration Building, 400 Bizzell St, College Station, TX 77843",
  "1210 Varsity Dr., E. Carroll Joyner Visitor Center, Raleigh, NC 27606",
  "1331 Cir Park Dr, Knoxville, TN 37916"
)

geocoding_data <- map(addresses, get_geocode_data)

# Define census API key
census_api_key("94d96c1dfb04afe285d0db958f78ded8a4b197f7")

get_population <- function(geographies) {
  # If geographies is NULL, return NA
  if (is.null(geographies)) {
    return(NA)
  }

  # Extract the state, county, tract, and block group
  state <- geographies$`2010 Census Blocks`[[1]]$STATE
  county <- geographies$`2010 Census Blocks`[[1]]$COUNTY
  tract <- geographies$`2010 Census Blocks`[[1]]$TRACT
  block_group <- geographies$`2010 Census Blocks`[[1]]$BLKGRP

  # Print out the geography parameters
  print(paste("State:", state))
  print(paste("County:", county))
  print(paste("Tract:", tract))
  print(paste("Block group:", block_group))

  # Get the total population for the block group
  population <- get_acs(
    geography = "block group",
    variables = "B01003_001",
    state = state,
    county = county,
    tract = tract,
    blockgroup = block_group
  )

  return(population$estimate)
}

# Get the total population for each block group
populations <- map(geocoding_data, get_population)

enter image description here

Fox_Summer
  • 149
  • 6

0 Answers0