gpt4 book ai didi

r - 如何找到最接近 R 中某个点的多边形?

转载 作者:行者123 更新时间:2023-12-03 18:33:37 28 4
gpt4 key购买 nike

我有一个空间点数据框和一个空间多边形数据框。例如,我的多边形是曼哈顿每个街区的多边形。点是人,他们分散在各处,有时落在街道中间,这不是多边形的一部分。

我知道如何检查一个点是否包含在一个多边形内,但我如何将点分配给它们最近的多边形?

## Make some example  data
set.seed(1)
library(raster)
library(rgdal)
library(rgeos)
p <- shapefile(system.file("external/lux.shp", package="raster"))
p2 <- as(1.5*extent(p), "SpatialPolygons")
proj4string(p2) <- proj4string(p)
pts <- spsample(p2-p, n=10, type="random")

## Plot to visualize
plot(pts, pch=16, cex=.5,col="red")
plot(p, col=colorRampPalette(blues9)(12), add=TRUE)

enter image description here

最佳答案

这是使用基于 mdsumner 在 this excellent answer 中描述的方法的答案。从几年前开始。

一个重要说明(添加为 编辑于 2/8/2015 ): rgeos ,这里用于计算距离,期望它操作的几何图形将在平面坐标中投影。对于这些示例数据,这意味着它们应该首先转换为 UTM 坐标(或其他一些平面投影)。如果您错误地将数据保留在其原始经纬度坐标中,则计算出的距离将是不正确的,因为它们会将纬度和经度视为具有相等的长度。

library(rgeos)

## First project data into a planar coordinate system (here UTM zone 32)
utmStr <- "+proj=utm +zone=%d +datum=NAD83 +units=m +no_defs +ellps=GRS80"
crs <- CRS(sprintf(utmStr, 32))
pUTM <- spTransform(p, crs)
ptsUTM <- spTransform(pts, crs)

## Set up containers for results
n <- length(ptsUTM)
nearestCanton <- character(n)
distToNearestCanton <- numeric(n)

## For each point, find name of nearest polygon (in this case, Belgian cantons)
for (i in seq_along(nearestCanton)) {
gDists <- gDistance(ptsUTM[i,], pUTM, byid=TRUE)
nearestCanton[i] <- pUTM$NAME_2[which.min(gDists)]
distToNearestCanton[i] <- min(gDists)
}

## Check that it worked
data.frame(nearestCanton, distToNearestCanton)
# nearestCanton distToNearestCanton
# 1 Wiltz 15342.222
# 2 Echternach 7470.728
# 3 Remich 20520.800
# 4 Clervaux 6658.167
# 5 Echternach 22177.771
# 6 Clervaux 26388.388
# 7 Redange 8135.764
# 8 Remich 2199.394
# 9 Esch-sur-Alzette 11776.534
# 10 Remich 14998.204

plot(pts, pch=16, col="red")
text(pts, 1:10, pos=3)
plot(p, add=TRUE)
text(p, p$NAME_2, cex=0.7)

enter image description here

关于r - 如何找到最接近 R 中某个点的多边形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26308426/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com