Home > Software design >  Finding length of shortest path between two vertices with igraph in r?
Finding length of shortest path between two vertices with igraph in r?

Time:06-29

This is my first time using igraph with r (also my first stack overflow question) and I'm trying to find a shortest path on a graph. I know how to use get_shortest_path to find the list of vertices that the shortest path would go through and that seems to work fine. My issue is that I cannot figure out easily how to find the distance. I know about the distance function but it seems to not find the distance on a directed graph. Here's an example on a simple graph

v1 = c("a","b")
v2 = c("ar","br")
weight = c(10,10)

test_df = data.frame(v1, v2, weight)
g <- test_df %>% graph_from_data_frame(directed = TRUE)

Running distances(g, "a", to="ar") returns 10 as expected

However running distances(g, "ar", to="a") also returns 10 despite there being no directed edge from ar to a

I tried looking at other questions but no one seemed to talk about directed edges. Is there something here I'm just completely missing?

CodePudding user response:

Specify the mode= argument. From the help file:

mode: Character constant, gives whether the shortest paths to or
      from the given vertices should be calculated for directed
      graphs. If ‘out’ then the shortest paths _from_ the vertex,
      if ‘in’ then _to_ it will be considered. If ‘all’, the
      default, then the corresponding undirected graph will be
      used, ie. not directed paths are searched. This argument is
      ignored for undirected graphs.

Taking that into account we have:

distances(g, "ar", to = "a", mode = "out")
##      a
## ar Inf

distances(g, "a", to = "ar", mode = "out")
##   ar
## a 10
  • Related