terra (version 0.3-7)

distance: Geographic distance

Description

If x is a SpatRaster:

If y is missing this method computes the distance, for all cells that are NA in SpatRaster x to the nearest cell that is not NA. If argument grid=TRUE, the distance is computed using a path that goes through the centers of the 8 neighboring cells.

If y is a SpatVector, the distance to that SpatVector is computed for all cells. For lines and polygons this is done after rasterization (for now).

If x is a SpatVector:

If y is missing, a distance matrix between all object in x is computed. An distance matrix object of class "dist" is returned.

If y is a SpatVector the geographic distance between all objects is computed (and a matrix is returned). If both sets have the same number of points, and pairwise=TRUE, the distance between each pair of objects is computed, and a vector is returned.

Usage

# S4 method for SpatRaster,missing
distance(x, y, grid=FALSE, filename="", overwrite=FALSE, wopt=list(), ...)

# S4 method for SpatRaster,SpatVector distance(x, y, filename="", overwrite=FALSE, wopt=list(), ...)

# S4 method for SpatVector,missing distance(x, y, ...)

# S4 method for SpatVector,SpatVector distance(x, y, pairwise=FALSE, ...)

Arguments

x

SpatRaster or SpatVector

y

missing or SpatVector

grid

logical. If TRUE, distance is computed using a path that goes through the centers of the 8 neighboring cells

filename

character. Output filename. Optional

overwrite

logical. If TRUE, filename is overwritten

wopt

list. Options for writing files as in writeRaster

...

additional arguments. None implemented

pairwise

logical. If TRUE and if x and y have the same size (number of rows), the pairwise distances are returned instead of the distances between all elements

Value

SpatRaster or numeric or matrix or distance matrix (object of class "dist")

The unit is in meters if the CRS is longlat and in map units (typically also meters) when it is not.

Examples

Run this code
# NOT RUN {
r <- rast(ncol=36,nrow=18)
v <- rep(NA, ncell(r))
v[500] <- 1
values(r) <- v
d <- distance(r) 
#plot(d / 100000)

# grid-distance
# g <- distance(r, grid=TRUE)


p1 <- vect(rbind(c(0,0), c(90,30), c(-90,-30)), crs="+proj=longlat +datum=WGS84")
dp <- distance(r, p1) 


d <- distance(p1)
d
as.matrix(d)

p2 <- vect(rbind(c(30,-30), c(25,40), c(-9,-3)), crs="+proj=longlat +datum=WGS84")
dd <- distance(p1, p2)
dd
pd <- distance(p1, p2, pairwise=TRUE)
pd
pd == diag(dd)
# }

Run the code above in your browser using DataLab