distMat | R Documentation |
Computes a distance matrix for a given set of spatial coordinates using a specified distance measure.
distMat(coords, CRS = NULL, dist_method = "auto", verbosity = 2)
coords |
data frame (or an object that can be coerced to such) with only two columns containing the spatial coordinates (x and y, or longitude and latitude, or easting and northing, in this order!) |
CRS |
Coordinate Reference System for 'coords' (if it is not a SpatVector with its CRS defined already), in one of the following formats: WKT/WKT2, <authority>:<code>, or PROJ-string notation (see |
dist_method |
The method to use for distance calculation. Partial and case-insensitive argument matching is used. Options are:
If a metric has the same name in 'terra' and 'geodist' and both packages are available, the latter is used, as it is slightly faster. |
verbosity |
integer specifying the amount of messages to display along the process. The default is 2, for the maximum amount of messages available. |
This function computes a matrix of pairwise distances for the input set of coordinates. It supports various distance measures by calling stats::dist()
, terra::distance()
or geodist::geodist()
, depending on the specified method and on the installed R packages.
With the default "auto" option, if neither terra
nor geodist
are installed, the method is "euclidean" from stats::dist()
. Otherwise, the method is "haversine" (relatively fast, but may be inaccurate at long distances, especially near the poles) if there are distances < 1 m or 0.00001 degrees; or "cosine" (faster but inaccurate for small distances) otherwise (unless 'terra' version is older than 1.8.7, when "cosine" was implemented). You can instead choose a specific option, e.g. "geo" or "geodesic" for the most accurate yet slowest distance method (see ?terra::distance; may crash if many points); "vincenty" (more accurate than "haversine" as it considers the Earth's ellipticity, but slower and may fail for nearly antipodal points); or "cheap" (the fastest, but inaccurate for maximum distances >100 km).
A matrix of distances between the coordinates.
A. Marcia Barbosa
# generate some random geographical coordinates:
n_points <- 10
set.seed(123)
coords <- matrix(c(runif(n_points, min = -180, max = 180),
runif(n_points, min = -90, max = 90)),
ncol = 2)
# compute distance matrix:
distMat(coords, dist_method = "euclidean")
distMat(coords, dist_method = "auto")
distMat(coords, dist_method = "auto", CRS = "EPSG:4326")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.