Calculate minimum distance between multiple polygons with R
Asked Answered
F

1

8

I'm still somewhat new to R and the sf package...

I have two sets of multipolygon data that I am trying to analyze. My first set of polygons (fires) contains hundreds of wildfire perimeters. The second set (towns) contains hundreds of urban areas boundaries.

For each fire, I would like to calculate the distance to the closest town (fire polygon edge to closest town polygon edge), and add that as a field to each fire.

So far I have mostly been using the sf package for spatial data. In my searches, I can only find minimum distance methods for polygons to points, points to points, lines to points, etc. but cannot seem to find polygon to polygon examples. Any help to send me in the right direction would be much appreciated! Thank you.

Finalize answered 19/12, 2018 at 15:51 Comment(3)
Does st_join(fires, towns, join = st_nearest_feature) do what you are after?Humeral
Thanks, I think that works for a spatial join. However, it doesn't seem to be giving me the distances between the joined polygons. Any idea how I might get it to put distance into an additional column?Finalize
You would need to use st_nearest_feature(fires, towns) which will give you the index of each nearest town for each fire. The you can use st_distance between those by setting pairwise = TRUE (I think - currently not at a computer).Humeral
F
9

@TimSalabim Thank you for sending me in the right direction. I was able to accomplish what I was after. Maybe not the most elegant solution, but it worked.

# create an index of the nearest feature
index <- st_nearest_feature(x = poly1, y = poly2)

# slice based on the index
poly2 <- poly2 %>% slice(index)

# calculate distance between polygons
poly_dist <- st_distance(x = poly1, y= poly2, by_element = TRUE)

# add the distance calculations to the fire polygons
poly1$distance <- poly_dist
Finalize answered 20/12, 2018 at 19:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.