# [R-sig-Geo] Computing pairwise minimum distance moving only within clipped area

Carrie Perkins cperk @end|ng |rom terpm@||@umd@edu
Sat Oct 12 21:37:16 CEST 2019

```Hello!

I am trying to compute pairwise minimum distances within a raster that has
been clipped to an outer boundary using a polygon.

I tried to do this using gDistance (reproducible example below) but am not
sure if it worked. I need to know the pairwise distances between patches
where the path travelled does not exit the clipped boundary (in the example
below, this is the border of Switzerland).

library(maptools)
library(raster)
data(wrld_simpl)
SPDF <- subset(wrld_simpl, NAME=="Switzerland") #polygon map of Switzerland
## Example RasterLayer
r <- raster(nrow=1000, ncol=1000, crs=proj4string(SPDF)) #blank raster

r[] <- 0 #set all cell values in raster to 0

## crop raster to extent of Switzerland polygon, SPDF
r2 <- crop(r, extent(SPDF))

#create patches by setting certain cells in raster to value 1; all other
cells are still 0

r2[8,1] <- 1
r2[9,11] <- 1

plot(r2)

p <- clump(r3) #give each patch of its own unique ID
spplot(p)

p[is.na(p[])] <- 0 #all cells that were previously 0 were set to NA by
clump() so we need to change them back to 0

p.masked <- mask(p,SPDF) #now clip the raster to the border of Switzerland
using SPDF; outside of Switzerland's border cells are now NA

rpoly <- rasterToPolygons(p.masked, dissolve=T) #convert from raster to
polygons; NA cells (outside Switzerland) do not get converted

d <- gDistance(rpoly, byid=T) #calculate minimum pairwise distances between
polygons

library(reshape2)
df <- melt(as.matrix(d), varnames = c("row", "col")) #put pairwise
distances into a dataframe

colnames(df) <- c("node_i_ID","node_j_ID","Distance")

df

I cannot tell whether gDistance did what I am trying to do, i.e. calculate
the minimum pairwise distances among patches without leaving the boundary
of Switzerland, or whether the path travelled includes areas outside of
Switzerland. If it is the latter, I could use some help figuring out a way
to keep the path travelled confined to the country boundary. Thanks!

[[alternative HTML version deleted]]

```