# Averaging accumulated cost surfaces/shortest paths [r] [gdistance]

I'm trying to find a way to be able to average two accumulated cost surfaces so I can find the optimal route from both A to B and B to A. Although the difference is cost surface is due to the travel direction, the travel route is the same for the origin and goal point, therefore I need to average these.

As can be seen, the accumulated cost surfaces are different based on whether the travel is from A to B or B to A. And so, the optimal route calculated differs. Is there a way to average the two accumulated cost surfaces to create a new cost surface that is based on both travels?

reproducible code:

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

altDiff <- function(x){x - x}
hd <- transition(r, altDiff, 8, symm=FALSE)

slope <- geoCorrection(hd)

adj <- adjacent(r, cells=1:ncell(r), pairs=TRUE, directions=8)
speed <- slope
speed[adj] <- 6 * exp(-3.5 * abs(slope[adj] + 0.05))

Conductance <- geoCorrection(speed)

A <- c(2667670, 6479000)
B <- c(2667800, 6479400)
AtoB <- shortestPath(Conductance, A, B, output="SpatialLines")
BtoA <- shortestPath(Conductance, B, A, output="SpatialLines")

AtoBacc <- accCost(Conductance, A)
BtoAacc <- accCost(Conductance, B)

par(mfrow=c(1,3))
plot(AtoBacc, main="A to B")
plot(BtoAacc, main="B to A")

plot(r, xlab="x coordinate (m)", ylab="y coordinate (m)", legend.lab="Altitude (masl)", main="Both")
lines(AtoB, col="red")
lines(BtoA, col="blue")
text(A - 10, A - 10, "A")
text(B + 10, B + 10, "B")
``````

I understand that the accumulated cost surface is a raster layer, and so I could just do a raster calculation. However, I would need to then convert it back into a transition layer, which would change the values.