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] 86602.821 225255.315 23180.430 14303.934 74146.245 37797.486
#> [7] 78697.785 164216.902 169194.822 49642.578 109982.003 5659.561
#> [13] 138036.462 24041.704 40204.860 93561.970 63165.072 126628.811
#> [19] 68865.047 122436.527 249407.147 73454.059 58556.261 85167.917
#> [25] 88872.924 40969.136 141723.182 107266.497 152430.802 31830.876
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] 529234.18 140466.84 297218.45 235912.56 405825.45 366228.14 387845.82
#> [8] 307230.50 56810.10 188559.62 384656.43 56039.33 197939.39 64590.64
#> [15] 380677.50 424683.97 306211.64 329921.62 350576.52 10862.22 27425.74
#> [22] 147273.29 205025.82 314994.06 31493.89 345919.82 81208.42 272412.99
#> [29] 179467.55 96501.76
hist(dist)