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

cod*_*art 2 r spatial r-grid

我想创建一个正方形网格,并标识边界一组其他网格单元格的网格单元格,二进制变量取1.在下面的示例中,我想生成一个边框ID为g13的单元格id的向量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))
Run Code Online (Sandbox Code Playgroud)

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

jba*_*ums 6

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 
Run Code Online (Sandbox Code Playgroud)

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

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

在此输入图像描述