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.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] 76158.89 254412.95 107602.44 71285.77 196834.15 246284.98 114131.38
#> [8] 127865.03 105894.85 131787.28 226724.24 96505.14 87023.11 11718.99
#> [15] 116266.01 80358.29 174489.64 212503.50 0.00 18795.10 59375.03
#> [22] 84271.03 35701.13 121144.63 114161.99 54626.76 5190.77 133178.95
#> [29] 92771.40 122502.83
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] 8180.195 104933.379 295498.963 120748.089 388455.066 337473.837
#> [7] 86273.899 28105.740 127427.339 289570.017 66051.274 112201.142
#> [13] 206097.699 321682.102 261371.640 482740.166 121025.955 239569.611
#> [19] 104886.889 261447.352 164956.330 266604.771 79150.919 414226.024
#> [25] 388698.535 92125.719 424134.391 382234.571 125786.804 246685.506
hist(dist)