r - 州多边形的相邻邮政编码
问题描述
第一次在 SO 上发帖
我有一个 shapefile,其中包含每个 Zipcode 的几何图形以及州名称。我想弄清楚哪些邮政编码位于州边界上。我想实现这一点的方法是结合每个州的所有邮政编码并导致一个州的几何形状,然后找到每个州的相邻邮政编码。
我使用以下方式将邮政编码组合成状态:
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 中传递邮政编码几何图形,但错误仍然存在。
任何帮助将不胜感激,也非常欢迎任何其他解决此问题的方法。
解决方案
考虑这个例子,它建立在随 {sf} 包分发的广泛可用的北卡罗来纳州 shapefile 上。
该示例的作用是:
通过首先解散县创建北卡罗来纳州的边界线,然后将生成的多面体转换为多线串
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
推荐阅读
- javascript - Vue中模态关闭后的动作
- java - 如何使用 Configuration.assertionMode = AssertionMode.SOFT; 混合框架(硒+硒化物)
- javascript - 包含带有特殊字符的字段的 JavaScript 解构对象
- javascript - if 语句中的正则表达式验证
- docker - Docker 启动失败 (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005)
- node.js - 如何使用listObjects在nodeJS中的IBM COS中单独获取嵌套文件
- python - ModuleNotFoundError 尽管软件包已正确安装
- c# - 使用 ASP.NET 在下拉菜单中显示 ID 和值
- bash - 有没有办法在 shell 脚本的 for cicle 循环中更改/清理变量?
- python - 在 python 中获取香港地理编码的问题