识别空间邻居并考虑 R 中的 NA (sp, rgeos)

Identify spatial neighbors and account for NAs in R (sp, rgeos)

我正在尝试将相邻的空间多边形识别为一组空间多边形,同时考虑邻居是否存在或是否为 NA。我正在使用 rgeos 包中的 gTouches() 函数来识别哪些几何图形共享一个公共边界,但是我不知道如何让它解释邻居的值​​是否为 NA,在这种情况下,我希望它找到下一个最接近的几何体。在下面的示例代码中,我希望包含 NA 的 tr2 的邻居不同于 tr:

library(rgeos)
library(sp)

grid <- GridTopology(c(0,0), cellsize = c(1,1), cells.dim = c(5,5)) 
poly <- as(grid, "SpatialPolygons")         
id <- names(poly)   

tr <- 13                            ### Define this as the grid for which to find neighbors         
g.id <- sprintf("g%i", tr)              ###     
tr <- ifelse(id %in% g.id, 1, 0)    
tr2 <- ifelse(id %in% g.id, 1, 0)   
tr2[8] <- NA

ex <- SpatialPolygonsDataFrame(poly, data = data.frame(id = id, tr = tr, tr2 = tr2, row.names = row.names(poly)))   
adj <- gTouches(poly, poly[which(ex$tr==1)], byid = TRUE)
nbrs <- as.vector(apply(adj,1,which))

adj2 <- gTouches(poly, poly[which(ex$tr2==1)], byid = TRUE)
nbrs2 <- as.vector(apply(adj2,1,which))

nbrs            
  [1]  7  8  9 12 14 17 18 19
nbrs2   ### Should be 2,3,4 (replace 8), 7, 9, 12, 14, 17, 18, 19
  [1]  7  8  9 12 14 17 18 19

关于如何做到这一点有什么想法吗?谢谢。

如果 nbrs2 中有 NA,您可以将初始多边形与 tr2 中具有 NA 的那个连接起来,然后在连接的多边形上使用 gTouches

library(maptools)
if(any(is.na(tr2[nbrs2]))) {
        to_join <- nbrs2[which(is.na(tr2[nbrs2]))]
        joined_polygon <- unionSpatialPolygons(poly[c(which(tr2==1),to_join)],rep(1,length(to_join)+1))
        adj2 <- gTouches(poly,joined_polygon,byid=TRUE)
        nbrs2 <- as.vector(apply(adj2,1,which))
}
nbrs2


#[1]  2  3  4  7  9 12 14 17 18 19

to_join 找到 tr2 中紧邻 13 且具有 NA 的多边形的编号。然后我们可以使用 maptools 中的 unionSpatialPolygons 连接多边形 13 和多边形 8,然后像您在代码中所做的那样使用 gTouches 找到所有相邻的多边形。