Calculate the least-cost distance between points.

costDistance(x, fromCoords, toCoords)

Arguments

x

object of class TransitionLayer

fromCoords

first set of point locations (of SpatialPoints, matrix or numeric class)

toCoords

optional, second set of point locations (of SpatialPoints, matrix or numeric class)

Value

distance matrix (S3 class dist or matrix)

Details

Cost units between cells are defined as the reciprocal of the values in the transition matrix.

The function uses Dijkstra's algorithm, as implemented in the igraph package.

A projection correction is needed for accuracy in the case of grid data for a longlat raster (see function geoCorrection).

References

E.W. Dijkstra. 1959. A note on two problems in connexion with graphs. Numerische Mathematik 1, 269 - 271.

See also

Author

Jacob van Etten

Examples

library("raster")
# create a new raster and set all its values to unity.
r <- raster(nrows=18, ncols=36)
r <- setValues(r,runif(ncell(r),0,1))

# create a Transition object from the raster
tr <- transition(r,function(x) 1/mean(x),8)
#> The extent and CRS indicate this raster is a global lat/lon raster. This means that transitions going off of the East or West edges will 'wrap' to the opposite edge.
#> Global lat/lon rasters are not supported under new optimizations for 4 and 8 directions with custom transition functions. Falling back to old method.

# asymmetric
ncf <- function(x) max(x) - x[1] + x[2]
tr2 <- transition(r,ncf,8, symm=FALSE)
#> The extent and CRS indicate this raster is a global lat/lon raster. This means that transitions going off of the East or West edges will 'wrap' to the opposite edge.
#> Global lat/lon rasters are not supported under new optimizations for 4 and 8 directions with custom transition functions. Falling back to old method.

# create two sets of coordinates
sP1 <- cbind(c(65,5,-65),c(55,35,-35))
sP2 <- cbind(c(50,15,-40),c(80,20,-5))

# from and to identical
costDistance(tr,sP1)
#>          1        2
#> 2 1.653010         
#> 3 3.917342 2.753792
costDistance(tr2,sP1)
#>          [,1]      [,2]     [,3]
#> [1,]   0.0000  6.245795 18.98641
#> [2,] 114.7071  0.000000 14.30999
#> [3,] 127.7512 14.912284  0.00000

# from and to different
costDistance(tr,sP1,sP2)
#>          [,1]      [,2]     [,3]
#> [1,] 1.037957 1.4737797 2.695152
#> [2,] 2.681768 0.8699277 1.639629
#> [3,] 4.935565 2.4718311 1.880000
costDistance(tr2,sP1,sP2)
#>           [,1]      [,2]      [,3]
#> [1,]  1.857573  9.881818 15.080932
#> [2,]  6.188271  5.851768 10.404515
#> [3,] 20.089880 15.020950  4.227604