来自状态多边形的相邻邮政编码

问题描述

第一次在 SO 上发帖

我有一个 shapefile,其中包含每个邮政编码的几何形状以及州名。我想弄清楚州边界上有哪些邮政编码。 我想实现这一点的方法是组合每个州的所有邮政编码并得出一个州的几何形状,然后找到每个州的相邻邮政编码。

我使用以下方法将邮政编码组合成州:

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

但是当我尝试使用 poly2nb

查找相邻的邮政编码时

state_nb <- poly2nb(st_geometry(state_shape))

它给了我一个错误

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

我知道要找到边界邮政编码,我必须在 poly2nb 中传递邮政编码几何图形,但错误仍然存​​在。

任何帮助将不胜感激,也欢迎任何其他解决此问题的方法

解决方法

考虑这个例子,它建立在广泛可用的北卡罗来纳州 shapefile 上,该文件与 {sf} 包一起分发。

示例的作用是:

  • 首先分解县,然后将生成的多边形转换为多线串,从而创建北卡罗来纳州的边界线

  • 在县和边界上运行 sf::st_touches(),稀疏设置为 false;结果是一个逻辑向量,可用于对原始 shapefile 进行子集化(过滤掉与 NC 边界共享边界的县)

  • 使用{ggplot2}以图形格式呈现结果;接壤的县是蓝色的,其余的只是空白

      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