Find nearest features using sf in R

时间:2018-03-09 19:00:10

标签: 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.

1 个答案:

答案 0 :(得分:4)

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,])),]
}