0
votes

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.

1
Following this logic, I assume you want 2 3 4 to replace 8, not just 3?Edzer Pebesma
Yes, that's right; editing that now.coding_heart

1 Answers

1
votes

If there is an NA in nbrs2, you could join the initial polygon with whichever has an NA in tr2 and use gTouches on the joined polygon:

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 find the number of the polygon that is next to 13 and has an NA in tr2. Then we can use unionSpatialPolygons from maptools to join polygon 13 and polygon 8, then use gTouches as you did in your code to find all the adjacent polygons.