The distanceto
package is designed to quickly sample
distances from points features to other vector layers. Normally the
approach for calculating distance to (something) involves generating
distance surfaces using raster based approaches eg.
raster::distance
or gdal_proximity
and
subsequently point sampling these surfaces. Since raster based
approaches are a costly method that frequently leads to memory issues or
long and slow run times with high resolution data or large study sites,
we have opted to compute these distances using vector based approaches.
As a helper, there’s a decidedly low-res raster based approach for
visually inspecting your region’s distance surface. But the workhorse is
distance_to
.
The distanceto
package provides two functions:
distance_to
distance_raster
distance_to
library(distanceto)
library(sf)
#> Linking to GEOS 3.12.1, GDAL 3.8.4, PROJ 9.4.0; sf_use_s2() is TRUE
# Load nc data
nc <- st_read(system.file("shape/nc.shp", package="sf"))
#> Reading layer `nc' from data source `/github/workspace/pkglib/sf/shape/nc.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> Geometry type: MULTIPOLYGON
#> Dimension: XY
#> Bounding box: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> Geodetic CRS: NAD27
# Set number of sampling points
npts <- 1e3
# Sample points in nc
ncpts <- st_sample(nc, npts)
# Select first 5 of nc
ncsub <- nc[1:5,]
# Measure distance from ncpts to first 5 of nc
dist <- distance_to(ncpts, ncsub, measure = 'geodesic')
# or add to ncpts
ncpts$dist <- dist
head(dist, 30)
#> [1] 100956.443 0.000 83726.897 0.000 99666.165 84247.525
#> [7] 70672.393 18410.030 5464.984 37302.895 99551.953 248905.692
#> [13] 74479.213 27398.312 39829.472 231115.298 117094.567 92528.287
#> [19] 66190.804 112982.444 82751.028 83333.131 36632.072 5788.318
#> [25] 93600.321 2256.344 61470.172 113843.232 112383.267 152881.976
hist(dist)
# Transform nc data to local projected coordinates (UTM 18N)
nc_utm <- st_transform(nc, 32618)
# Set number of sampling points
npts <- 1e2
# Sample points within nc data
nc_utm_pts <- st_sample(nc_utm, npts)
# Select one polygon within nc data
nc_utm_select <- nc_utm[1, ]
# Measure distance from seine points to seine
dist <- distance_to(nc_utm_pts, nc_utm_select)
# or add to seine points
nc_utm_pts$dist <- dist
head(dist, 30)
#> [1] 392538.77 305130.07 79165.93 377174.69 435015.24 414834.04 128997.33
#> [8] 339986.82 140999.01 131105.83 119029.25 428443.96 293204.60 350863.42
#> [15] 225887.12 480159.89 385646.58 365476.50 405183.68 343522.39 207812.82
#> [22] 23464.56 259304.98 114905.10 171522.70 276621.57 184741.83 147740.33
#> [29] 342605.92 283566.48
hist(dist)