I am trying to identify the neighborhing spatial polygon to a set of spatial polygons, while accounting for whether a neighbor exists or is NA. I'm using the gTouches()
function from the rgeos
package to identify which geometries share a common border, however I don't know how to make it account for whether the value of the neighbor is an NA, in which case I would like it to find the next closest geometry. In the following example code, I would like the neighbors for tr2
, which includes an NA, to be different than 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
Any thoughts on how to do this? Thanks.
2 3 4
to replace8
, not just3
? – Edzer Pebesma