R – Getting a New Column with Distance to the Nearest Feature

rsf

Having two sf data frames (a is points and b is polygons),
I can get columns from the nearest feature by for instance:

c <- st_join(a, b, st_nearest_feature), 

But how is the best way to get an additional column with the distance as well?

Best Answer

Don't do the join. st_nearest_feature(a,b) will get you the index (row number) of the nearest feature in b to each feature in a.

EG using data p and l from ?st_nearest_feature made into sf data frame:

> (nearest = st_nearest_feature(p,l))
[1] 1 2 2 3

Then use st_distance to get the element-wise distances between each element of p and the corresponding element of l:

> (dist = st_distance(p, l[nearest,], by_element=TRUE))
[1] 0.10 0.01 0.01 0.10

You could use the nearest index to do the join like this:

> (pljoin = cbind(p, st_drop_geometry(l)[nearest,]))
Simple feature collection with 4 features and 2 fields
geometry type:  POINT
dimension:      XY
bbox:           xmin: 0.1 ymin: -0.1 xmax: 0.1 ymax: 0.9
epsg (SRID):    NA
proj4string:    NA
  id st_drop_geometry.l..nearest...         geometry
1  a                              A POINT (0.1 -0.1)
2  b                              B POINT (0.1 0.11)
3  c                              B POINT (0.1 0.09)
4  d                              C  POINT (0.1 0.9)

(Column names are a bit mashed up but maybe you can work with that)

Then add the distance:

> pljoin$dist = dist
> 
Related Question