R/shortest_path.R

Defines functions shortest_path

Documented in shortest_path

#' Calculate shortest path
#'
#' Calculates shortest route based on distance or any other metric (e.g. time)
#' that you can specify using column name.
#'
#' @param graph tbl_graph object
#' @param from_node node ID for starting point
#' @param to_node vector of node IDs for end points
#' @param weigth optional. Which weight to use for optimization.
#' Defaults to using the distance as weight (i.e. shortest path using distance).
#'
#' @return igraph.es object with the optimal route
#'
shortest_path <- function(graph, from_node, to_node, weight = NULL) {
  
  library(igraph)
  library(tidygraph)
  library(dplyr)
  
  graph <- graph %>%
    activate(edges) %>%
    mutate(length = st_length(geometry))
  
  from_node <- graph %>%
    activate(nodes) %>%
    filter(nodeID %in% from_node) %>%
    pull(nodeID)
  
  to_node <- graph %>%
    activate(nodes) %>%
    filter(nodeID %in% to_node) %>%
    pull(nodeID)
  
  path <- shortest_paths(
    graph = graph,
    from = from_node,
    to = to_node,
    output = 'epath',
    weights = graph %>% 
      activate(edges) %>% 
      pull(ifelse(!is.null(weight), weight, length))
  )
  
  return(path$epath)
}
kjetilhaukas/shortestpath documentation built on April 28, 2022, 12:06 a.m.