I have a binary raster which I've classified into patches using
raster::clump. I now want to efficiently calculate the edge-to-edge, i.e. minimum, pairwise distance between patches. I am currently doing this by converting to polygons then using
rgeos::gDistance; however, I need to do this with a large number of large rasters and I'm hoping there's a more efficient and direct method avoiding the conversion.
Here's what I have so far:
library(raster) library(igraph) library(rgeos) # 10x10 UTM raster with 1km resolution utm10 <- crs('+proj=utm +zone=10 +ellps=GRS80 +datum=NAD83 +units=m +no_defs') r <- raster(extent(c(0, 10000, 0, 10000)), nrows=10, ncols=10, crs=utm10) patchCells <- c(1, 2, 35, 45, 62, 87, 88, 89, 98, 99, 100) r[patchCells] <- 1 # Classify into patches p <- clump(r, directions=8, gaps=F) spplot(p) # rasterToPolygon method rpoly <- rasterToPolygons(p, dissolve=T) d <- gDistance(rpoly, byid=T)
1 2 3 4 1 0.000 2828.427 5000.000 8062.258 2 2828.427 0.000 2236.068 3162.278 3 5000.000 2236.068 0.000 4123.106 4 8062.258 3162.278 4123.106 0.000
Edited to add some additional info: This will ideally be part of optimization exercise using simulated annealing. Therefore calculating these distances will need to be done many thousands of times as the algorithm progresses. Hence the need for efficiency. I'm hoping to keep this within R, but if it turns out there's no more efficient approach than what I already have, I'll likely look to using other tools, like C.