Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find nearest features using sf in R

Tags:

r

sf

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.

like image 554
mweber Avatar asked Mar 09 '18 19:03

mweber


Video Answer


1 Answers

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,])),]
}
like image 168
mweber Avatar answered Oct 10 '22 10:10

mweber