Neighboring Zipcodes from State Polygons

225 views Asked by At

First time posting on SO

I have a shapefile that has the geometries for each Zipcode along with state name. I want to figure out which zipcodes lie on the state borders. The way I figured to achieve this is by combining all zipcodes for each state and leading to the geometry for a state and then finding the neighboring zipcodes for each state.

I combined the zipcodes into states using:

state_shape <- shapefile %>% group_by(State) %>% summarise(geometry = sf::st_union(geometry))

But then when I try to find the neighboring zipcodes using poly2nb

state_nb <- poly2nb(st_geometry(state_shape))

It gives me an Error:

Error in poly2nb(st_geometry(state_shape)) : Polygon geometries required

I understand to find the border zipcodes I will have to pass the zipcode geometries in poly2nb, but the error persists.

Any help will be highly appreciated, also any other approaches to this problem are more than welcome.

1

There are 1 answers

0
Jindra Lacko On

Consider this example, built on the widely available North Carolina shapefile that is distributed with {sf} package.

What the example does is:

  • creates a border line of North Carolina by first dissolving the counties, and then casting the resulting multipolygon to a multilinestring

  • runs sf::st_touches() on the counties and borderline with sparse set to false; the result is a logical vector that can be used to subset the original shapefile (filtering out the counties that share a border with the NC border)

  • presents the results in a graphical format, using {ggplot2}; the bordering counties are blue and the rest just blank for context

      library(sf)
      library(dplyr)
      library(ggplot2)
    
      # all NC counties (from shapefile distributed with {sf})
      shape <- st_read(system.file("shape/nc.shp", package="sf")) 
    
      # border, via dplyr::summarise() & cast as a linestring
      border <- shape %>% 
        summarise() %>% 
        st_cast("MULTILINESTRING")
    
      # logical vector of length nrow(shape)
      neighbours <- sf::st_touches(shape,
                                   border,
                                   sparse = F)
      # report results
      ggplot() +
        geom_sf(data = shape[neighbours, ], fill = "blue") + # border counties
        geom_sf(data = shape, fill = NA, color = "grey45") # all counties for context
    

enter image description here