0
votes

I would like to calculate the distances between each polygon in a shapefile using the sf package (or other packages that potentially works). I prefer the distance to be the maximum or minimum distance (as I don't know how to set up these parameters). As an example, suppose there are three polygons in a shapefile namely polygon A, B and C, the result I would like to get would be a data frame that says the distance between A to B, A to C, B to C.

For an example shapefile, you can use the sf inbuilt example shapefile by code below:

library(sf) 
counties <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = T)

Any hint will be much appreciated :) Thanks in advance for your help!

1

1 Answers

1
votes

You are likely looking for the sf::st_distance() function.

It supports polygon to polygon distances, so it will give you the shortest distance between two county polygons in the NC shapefile as a matrix. In case of neighboring polygons this will be zero.

In order to make the matrix easier to work with you may want to set the rownames and colnames; these can be then used for subsetting.

Consider this code:

library(sf) 
counties <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = T)

# matrix of county to county distances
distances <- st_distance(counties, counties)

# create colnames and rownames to make work easier
colnames(distances) <- counties$NAME
rownames(distances) <- counties$NAME

# distance from county Mecklenburg / 100 values, inc. zeroes
distances["Mecklenburg",] 

# counties bordering Mecklenburg cnty / 6 counties - just the zeroes from example above
distances[distances["Mecklenburg", ] == units::as_units(0, "meter"), "Mecklenburg"]