0
votes

There are X numbers of functions in R to calculate the shortest distances between two polygons, but I can't seem to find a way to make the functions return between which two locations this distance is?!

Let say that the distance between polygon A and B is 10 units. My question is then, between which two points on A and B can I draw the line that is 10 units.

Is all the Christmas food clogging my brain?

1
Can you make this reproducible? I don't know what type of data you're working with, what code you've written, what approach you're taking, what these other functions are that don't do what you want, etc. - camille
What does your data look like? sf, sp, other? Help us help you! - mrhellmann

1 Answers

1
votes

If you can get your data into an sf object(s), then sf::st_nearest_points() will do the job.

Below is an example with toy data:

library(sf)

p1 <- matrix(c(0, 0, 1, 0, 1, 1, 0, 1, 0, 0), ncol = 2, byrow = TRUE)

p2 <- p1 + 3

pts1 <- list(p1)
pts2 <- list(p2)

poly1 <- st_polygon(pts1)
poly2 <- st_polygon(pts2)

near_points <- st_nearest_points(poly1, poly2)

Near points returns an sf LINESTRING object with two points(1,1) and (3,3):

Geometry set for 1 feature 
geometry type:  LINESTRING
dimension:      XY
bbox:           xmin: 1 ymin: 1 xmax: 3 ymax: 3
epsg (SRID):    NA
proj4string:    NA
LINESTRING (1 1, 3 3)
ggplot() + geom_sf(data = poly1, color = 'blue') +
  geom_sf(data = poly2, color = 'orange') +
  geom_sf(data = near_points, color = 'red')

enter image description here

st_distance() will return the distance between the two closest points.

 st_distance(poly1, poly2)
         [,1]
[1,] 2.828427