areddy
areddy

Reputation: 383

How to get sum of maximum time taken to travel between few locations?

I have a matrix containing times taken to travel from every location to the other say

library(geosphere)
lat<-c(17.48625,17.49412,17.51925,17.49359,17.49284,17.47077)
long<-c(78.38951,78.39643,78.37823,78.40079,78.40686,78.35874)
xy = data.frame(x=long,y=lat)
dmat = outer(1:nrow(xy), 1:nrow(xy), function(i,j) distHaversine(xy[i,],xy[j,]))
tmat = dmat/(333.33)  #333.33 is speed in meters/minute. time will be in minutes

Suppose I give a vector of locations say c(point1,point3,point4) (here the points represents rownumbers or column names of tmat), how can I get the maximum time taken to travel any route connecting these points, t1+t2+t3?

Upvotes: 1

Views: 46

Answers (1)

cocquemas
cocquemas

Reputation: 1149

Say you want to travel from point 1 to point 4 to point 3:

points <- c(1,4,3)

Now, you want to consider all permutations of those points. One way to get them is to use gtools::permutations:

library(gtools)
itineraries <- permutations(length(points), length(points), points)

For a given itinerary, you can compute the times between each successive two points and sum over them, with this function:

itinerary.time <- function(itinerary) {
  sum(sapply(2:length(itinerary), function(i) 
    tmat[itinerary[i-1], itinerary[i]]))
}

And then simply apply the function across the rows and take the max of the times:

max(apply(itineraries, 1, itinerary.time))

This extends to an arbitrary number of points.

Upvotes: 2

Related Questions