Let's set up some sample data:
library(sp)
library(spdep)
example(columbus)
plot(columbus)
We'll now get some points. Click 20 times on the map, some inside and some outside polygons:
pts = locator(20,type="p")
Convert to Spatial data type:
spts = SpatialPoints(pts)
Now use rgeos
to compute point-polygon distances, and take the minimum for each point:
library(rgeos)
> apply(gDistance(spts, columbus,byid=TRUE),2,min)
1 2 3 4 5 6 7
0.25947439 0.03898401 1.27156515 1.50490316 0.00000000 0.00000000 0.00000000
8 9 10 11 12 13 14
0.00000000 0.00000000 0.31312329 0.26742466 0.53934325 0.07764322 0.03909773
15 16 17 18 19 20
0.11156343 0.29243322 0.08872334 0.00000000 0.00000000 0.00000000
There you go. That's the minimum distance from each of the 20 points to any of the polygons. The zeroes are for points inside one of the polygons.
Note you should use data in a projected spatial coordinate system and not lat-long.
If you have 17,000 points then you might want to do this in smaller subsets to avoid creating a 17,000 x 5,000 matrix if you have 5,000 polygons. You didn't say.
I will assume that you can use dplyr
if not you can adapt to base R
.
Here's a solution
library(sf)
library(dplyr)
RST_WIDTH <- 123
tab_ds <- data.frame(ux = c( 1, 2, -3),
uy = c(-1, -2, -3)) %>%
mutate(w = RST_WIDTH, h = RST_WIDTH)
tab_ds %>%
rowwise() %>%
mutate(geometry = list(sf.rect.xywh(ux, uy, w, h))) %>%
st_as_sf(sf_column_name = "geometry")
## Simple feature collection with 3 features and 4 fields
## geometry type: POLYGON
## dimension: XY
## bbox: xmin: -64.5 ymin: -64.5 xmax: 63.5 ymax: 60.5
## CRS: NA
## # A tibble: 3 x 5
## # Rowwise:
## ux uy w h geometry
## <dbl> <dbl> <dbl> <dbl> <POLYGON>
## 1 1 -1 123 123 ((-60.5 60.5, 62.5 60.5, 62.5 -62.5, -…
## 2 2 -2 123 123 ((-59.5 59.5, 63.5 59.5, 63.5 -63.5, -…
## 3 -3 -3 123 123 ((-64.5 58.5, 58.5 58.5, 58.5 -64.5, -…
Hope it helps
Best Answer
Don't do the join.
st_nearest_feature(a,b)
will get you the index (row number) of the nearest feature inb
to each feature ina
.EG using data
p
andl
from?st_nearest_feature
made intosf
data frame:Then use
st_distance
to get the element-wise distances between each element ofp
and the corresponding element ofl
:You could use the nearest index to do the join like this:
(Column names are a bit mashed up but maybe you can work with that)
Then add the distance: