R/to_igraph.R

Defines functions to_igraph

Documented in to_igraph

#' Convert cppRouting graph to an igraph object
#'
#' @param Graph  An object generated by cppRouting::makegraph() or cpp_simplify() function.
#' @param aux logical. If \code{TRUE}, carry the graph's \code{aux} weight(s) over as edge attribute(s). See
#' \link{to_df}.
#' @param capacity logical. If \code{TRUE}, carry \code{capacity} over as an edge attribute.
#' @param alpha logical. If \code{TRUE}, carry \code{alpha} over as an edge attribute.
#' @param beta logical. If \code{TRUE}, carry \code{beta} over as an edge attribute.
#' @return An \code{igraph} object. Requires the \code{igraph} package.
#' @details Vertices are named after the graph's own node refs (\code{Graph$dict$ref}); if the graph has
#' coordinates, they are attached as vertex attributes \code{x}/\code{y}. Edge cost (\code{dist}) is exposed
#' as the edge attribute \code{weight}, matching igraph's own convention for its shortest-path functions
#' (\code{igraph::distances()}, \code{igraph::shortest_paths()}, etc. use \code{weight} by default) -- so the
#' result is directly usable with igraph's own algorithms (centrality, community detection, plotting...)
#' without cppRouting needing to reimplement any of them.
#' @examples
#' #Simple directed graph
#'
#' edges<-data.frame(from=c(1,2,3,4,5,6,7,8),
#' to=c(0,1,2,3,6,7,8,5),
#' dist=c(1,1,1,1,1,1,1,1))
#'
#' #Construct cppRouting graph
#' graph<-makegraph(edges,directed=TRUE)
#'
#' #Convert cppRouting graph to an igraph object
#' if (requireNamespace("igraph", quietly = TRUE)) {
#'   ig <- to_igraph(graph)
#' }


to_igraph<-function(Graph, aux = FALSE, capacity = FALSE, alpha = FALSE, beta = FALSE){
  Graph <- tag_legacy_graph(Graph)

  if (!inherits(Graph, "cppRouting_graph")) stop("Invalid graph input, must be an object generated by makegraph() or cpp_simplify() function")
  if (!requireNamespace("igraph", quietly = TRUE)) stop("Package 'igraph' is required for to_igraph()")

  edges <- to_df(Graph, aux = aux, capacity = capacity, alpha = alpha, beta = beta)
  names(edges)[names(edges) == "dist"] <- "weight"

  vertices <- data.frame(name = Graph$dict$ref, stringsAsFactors = FALSE)
  if (!is.null(Graph$coords)) {
    vertices$x <- Graph$coords[[2]]
    vertices$y <- Graph$coords[[3]]
  }

  igraph::graph_from_data_frame(edges, directed = TRUE, vertices = vertices)
}

Try the cppRouting package in your browser

Any scripts or data that you put into this service are public.

cppRouting documentation built on Nov. 12, 2026, 5:11 p.m.