Skip to content

Instantly share code, notes, and snippets.

@grantmcdermott
Last active January 23, 2020 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grantmcdermott/9500e215117852e2cfcc844d88b7a469 to your computer and use it in GitHub Desktop.
Save grantmcdermott/9500e215117852e2cfcc844d88b7a469 to your computer and use it in GitHub Desktop.
Get (possible) census tracts for address based on zip code
## Context: https://twitter.com/grant_mcdermott/status/1220409051013697553
library(tidycensus)
# census_api_key("YOUR KEY GOES HERE", install = TRUE)
library(tigris)
options(tigris_use_cache = TRUE)
library(sf)
library(tidyverse)
## Get ZIP codes for whole US. First time you run this it will take a while, but
## caching means it will be available for future sessions
zips = get_acs(geography = "zcta", variables = "B19013_001", geometry = TRUE)
## Get OH Census tracts
oh = get_acs(geography = "tract", state = "OH", variables = "B19013_001", geometry = TRUE)
## Spatial join
oh =
st_join(
oh %>% rename(tract = NAME),
zips %>% select(zip = NAME, geometry)
)
## Some extra cleaning up
oh =
oh %>%
mutate(
tract = gsub("Census Tract ", "", tract),
zip = as.numeric(gsub("ZCTA[0-9] ", "", zip))
)
## Now you can match on zip code for addresses.
## E.g. Ohio Statehouse (1 Capitol Square, Columbus, OH 43215)
ohsh = tibble(street = "1 Capitol Square",
Columbus, OH 43210
city = "Columbus",
state = "OH",
zip = 43215)
## Join to get tract
ohsh_tract =
left_join(
ohsh,
oh,
by = "zip"
)
## Plot
ohsh_tract %>%
st_as_sf() %>%
ggplot() +
geom_sf()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment