The 'gdistance' R package is really useful in calculating least-cost paths (hereafter LCP) between locations. I have successful used some published material (LINK) for my purposes.

What I'd like to achieve

Let's assume we calculate the LCP between A and B implementing the Tobler's hiking function, so considering the slope as cost factor. We can proficiently use 'gdistance' to calculate the LCP (more below). Now, I would like to calculate the second best LCP. I thought of:

  • calculating the LCP
  • setting to NA the cells of the input raster corresponding to the LCP
  • re-calculating the LCP to obtain what (to my mind) would be the second "best" LCP

Some reproducible code to show what I achieved and where the issue lies

The following code is from the published material whose LINK is provided above.


r <- raster(system.file("external/maungawhau.grd", package="gdistance"))

heightDiff <- function(x){x[2] - x[1]}
hd <- transition(r,heightDiff,8,symm=FALSE)
slope <- geoCorrection(hd, scl=FALSE)
adj <- adjacent(r, cells=1:ncell(r), pairs=TRUE, directions=8)
speed <- slope
speed[adj] <- exp(-3.5 * abs(slope[adj] + 0.05))

x <- geoCorrection(speed, scl=FALSE)

A <- c(2667670,6479000)
B <- c(2667800,6479400)

AtoB <- shortestPath(x, A, B, output="SpatialLines")

plot(AtoB, add=T)

As expected, the above code produces the following: enter image description here

Now, the following code use the raster::mask() function to set to NA the raster cells corresponding to the LCP calculated above, and repeat the above code using the masked raster, i.e. the Digital Terrain Model purged (so to speak) from the first LCP.

masked_r <- raster::mask(r, AtoB, inverse=TRUE)

hd <- transition(masked_r,heightDiff,8,symm=FALSE)
slope <- geoCorrection(hd, scl=FALSE)
adj <- adjacent(masked_r, cells=1:ncell(masked_r), pairs=TRUE, directions=8)
speed <- slope
speed[adj] <- exp(-3.5 * abs(slope[adj] + 0.05))

x <- geoCorrection(speed, scl=FALSE)

AtoB_bis <- shortestPath(x, A, B, output="SpatialLines")

plot(AtoB_bis, add=T)

The result is in the image below: enter image description here


I do not understand why what could be considered (to my mind) the second "best" LCP at times passes through and/or crosses cells that had been given NA in the "purged" DTM. I was expecting that the second LCP would have "avoided" the locations (i.e., cells) previously "visited" by the first LCP.

1 Answer 1


Maybe if you set the cells of the first path to a very high cost, rather than NA, the second path would avoid them?

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .