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.11.2, GDAL 3.7.0, PROJ 9.2.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
#> `/home/alecr/R/x86_64-pc-linux-gnu-library/4.3/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] 85854.15 214115.16 114722.81 27125.61 58608.00 146476.07 70632.84
#> [8] 62467.30 70865.31 45025.02 112034.69 96857.95 20927.66 96153.15
#> [15] 15079.88 167950.77 176145.61 138975.09 36948.58 176156.59 260573.32
#> [22] 62151.46 148009.81 144507.36 108652.05 22275.69 132555.32 82302.40
#> [29] 81019.47 15510.67
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] 185605.20 217897.05 373945.35 67954.77 203383.63 103585.02 296722.36
#> [8] 121457.95 186440.08 63704.97 399608.41 41812.09 158345.13 145320.48
#> [15] 322582.02 56782.90 358115.92 99134.63 263733.30 96413.27 125083.77
#> [22] 296417.19 83560.10 180529.03 12400.41 382581.03 125794.03 383618.63
#> [29] 210497.31 30590.28
hist(dist)