Skip to content

Instantly share code, notes, and snippets.

@walkerke
Created January 18, 2023 21:01
Show Gist options
  • Save walkerke/da5080c3116ace0c618ddf43f4e2c2fd to your computer and use it in GitHub Desktop.
Save walkerke/da5080c3116ace0c618ddf43f4e2c2fd to your computer and use it in GitHub Desktop.
library(tidycensus)
library(tigris)
library(tidyverse)
library(sf)
options(tigris_use_cache = TRUE)
sf_use_s2(FALSE)
top_places <- get_acs(
geography = "place",
variables = "B01001_001",
geometry = TRUE,
year = 2021,
survey = "acs1",
keep_geo_vars = TRUE
) %>%
filter(LSAD == "25") %>%
slice_max(estimate, n = 50)
us_tracts <- tracts(cb = TRUE, year = 2021)
intersect_within_ratio <- top_places %>%
split(~NAME.x) %>%
imap_dfr(~{
num_overlaps <- nrow(st_filter(us_tracts, .x, .predicate = st_overlaps))
num_within <- nrow(st_filter(us_tracts, .x, .predicate = st_within))
tibble(name = .y,
inter = num_overlaps + num_within,
within = num_within) %>%
mutate(ratio = inter / within) %>%
rename(City = name,
`Overlaps or within` = inter,
`Within only` = within,
`Ratio` = ratio)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment