I'm trying to take a dataset of ZIP codes and limit it to just ZIP codes within Chicago. However, any way I try to do this merge captures either far too many or too few ZIP codes. Here's a reproducible example:
## Load packages
library(tigris)
library(sf)
library(ggplot2)
## Load shapefiles
ZIPs <- tigris::zctas(cb = TRUE)
ZIPs <- sf::st_as_sf(ZIPs)
places <- tigris::places(state = "17", cb = T)
chicago <- places[places$NAME == "Chicago",]
chicago <- sf::st_as_sf(chicago)
## Filter ZIPs to those within Chicago using st_intersects
overlap <- st_filter(ZIPs, chicago, .predicate = st_intersects) #Using st_intersects captures too many ZIPs
## Visualize ZIPs vs Chicago
ggplot() +
geom_sf(data = overlap, color = "black", size = 1) +
geom_sf(data = chicago, color = NA, fill = "blue", alpha = .25)
## Try again using st_within
overlap <- st_filter(ZIPs, chicago, .predicate = st_within) #Using st_within captures too few ZIPs
## Visualize ZIPs vs Chicago
ggplot() +
geom_sf(data = overlap, color = "black", size = 1) +
geom_sf(data = chicago, color = NA, fill = "blue", alpha = .25)
I've also tried to use sp::over for this task but run into the same problem. There are clearly some ZIPs that are mostly outside of Chicago, but legitimately have some overlap (e.g. the three ZIPs on the top left of the first map). However there are others that only intersect along a border (e.g. top right), and even one that doesn't appear to intersect at all (bottom right). I want to exclude from this map any ZIPs that only intersect by border. Any advice?


