14

I'm wanting to find the nearest polygons in a simple features data frame in R to a set of points in another simple features data frame using the sf package in R. I've been using 'st_is_within_distance' in 'st_join' statements, but this returns everything within a given distance, not simply the closest features.

Previously I used 'gDistance' from the 'rgeos' package with 'sp' features like this:

m = gDistance(a, b, byid = TRUE)
row = apply(m, 2, function(x) which(x == min(x)))
labels = unlist(b@data[row, ]$NAME)
a$NAME <- labels

I'm wanting to translate this approach of finding nearest features for a set of points using rgeos and sp to using sf. Any advice or suggestions greatly appreciated.

mweber
  • 739
  • 1
  • 6
  • 17
  • 2
    Reprex would be great. Can't you do basically the same thing - map through the points doing `which.min(st_distance(point, polygons))`? – Calum You Mar 09 '18 at 19:18
  • 2
    `st_nearest_feature` might come handy here? https://r-spatial.github.io/sf/reference/st_nearest_feature.html – radek Oct 05 '20 at 10:50

1 Answers1

14

It looks like the solution to my question was already posted -- https://gis.stackexchange.com/questions/243994/how-to-calculate-distance-from-point-to-linestring-in-r-using-sf-library-and-g -- this approach gets just what I need given an sf point feature 'a' and sf polygon feature 'b':

closest <- list()
for(i in seq_len(nrow(a))){
    closest[[i]] <- b[which.min(
    st_distance(b, a[i,])),]
}
Matt
  • 490
  • 8
  • 19
mweber
  • 739
  • 1
  • 6
  • 17
  • 5
    If you want to find the shortest distance between all points in the same sf feature, you can use `closest[[i]] <- a[which.min(st_distance(a[-i,], a[i,])),]`. The `-i` removes the current row from the distance matrix calculation so you don't return zero. – Matt May 10 '18 at 19:53