# R (gdistance): least cost path passing through and/or crossing cells with NA

Intro

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.

``````library(gdistance)

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)
speed <- slope

x <- geoCorrection(speed, scl=FALSE)

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

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

plot(r)
``````

As expected, the above code produces the following:

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)

slope <- geoCorrection(hd, scl=FALSE)
speed <- slope

x <- geoCorrection(speed, scl=FALSE)

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