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_todistance_rasterdistance_tolibrary(distanceto)
library(sf)
#> Linking to GEOS 3.14.1, GDAL 3.12.2, PROJ 9.7.1; 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] 51465.534 96592.997 0.000 79053.549 35235.782 5858.892
#> [7] 104633.784 96142.241 0.000 0.000 161797.633 156180.758
#> [13] 14195.462 265899.632 71859.389 34055.312 209623.609 75420.779
#> [19] 18230.063 111924.084 3840.981 120028.840 11453.015 172220.289
#> [25] 0.000 32754.779 214577.227 43689.145 71771.741 79112.256
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] 74291.92 427973.91 323029.24 11721.62 383605.98 248120.25 366917.66
#> [8] 324257.15 316263.52 376536.81 383331.11 338915.52 313071.25 0.00
#> [15] 224044.27 64367.02 412840.57 106826.42 128152.61 189357.24 258113.67
#> [22] 297382.01 228909.69 194082.56 63986.25 31537.03 232868.49 219570.19
#> [29] 345927.47 63821.66
hist(dist)