r - 识别 R 中网格中最近的邻居(空间)

标签 r spatial r-grid

我想创建一个正方形网格并识别与一组其他网格单元相邻的网格单元,其二进制变量取 1。在下面的示例中,我想生成一个单元格 ID 的向量,该单元格 ID 与边界相邻id g13 和 g24:

require(sp)         
grid <- GridTopology(c(0,0), c(1,1), c(5,5))    
polys <- as(grid, "SpatialPolygons")
centroids <- coordinates(polys)
id <- names(polys)
tr <- ifelse(id == "g13" | id == "g24", 1, 0)       
ex <- SpatialPolygonsDataFrame(polys, data = data.frame(id = id, tr = tr, row.names = row.names(polys)))

plot(ex)
text(coordinates(polys), labels = row.names(polys))

这样它输出一个向量,所有匹配的 g13 为 (g7, g8, g9, g12, g14, g17, g18, g19) 和一个匹配的 g24 为 (g18, g19, g20, g23, g24, g25)。非常感谢任何和所有的想法。

最佳答案

rgeos::gTouches 非常适合这个:

library(rgeos)
adj <- gTouches(polys, polys[which(ex$tr==1)], byid=TRUE)
apply(adj, 1, which)

# $g13
#  g7  g8  g9 g12 g14 g17 g18 g19 
#   7   8   9  12  14  17  18  19 
# 
# $g24
# g18 g19 g20 g23 g25 
#  18  19  20  23  25 

而且,因为每个人都喜欢图片:

plot(ex, col=ifelse(seq_along(ex) %in% c(unlist(adj), which(ex$tr==1)), 'gray', NA))
text(coordinates(polys), labels=row.names(polys))

enter image description here

关于r - 识别 R 中网格中最近的邻居(空间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27810015/

相关文章:

r - 在图例ggplot中显示实心箭头

r - 按 R 中的因子计算多边形内的点

c# - 包含 SqlGeometry 的数据表导致存储过程执行失败...为什么?

r - 如何确定 pointsGrob 的大小(相对于 textGrob 的大小)?

r - 将图像与 r 中的数据框连接起来

r - 如何在R中安装tcltk?

R 内存管理/无法分配大小为 n Mb 的向量

r - R中非空数值向量的维数

c# - RavenDB 空间搜索始终为空

删除 ggplot 周围的彩色边框