2

I am trying to obtain edge lists of paths between two nodes using tidygraph. Here is an example

demo <- tbl_graph(nodes = tibble(name = c("A", "B", "C", "D")),
                       edges = tribble(~from, ~to,~id,
                                       "B", "A", "1",
                                       "D", "C", "2",
                                       "A", "D", "3",
                                       "A", "C", "4"),
                   node_key = "name")

I used all_simple_paths from igraph package to obtain all possible paths between node B and node C.

paths <- all_simple_paths(demo, "B", "C")
#[[1]]
#+ 3/4 vertices, named, from e0c8c2e:
#[1] B A C

#[[2]]
#+ 4/4 vertices, named, from e0c8c2e:
#[1] B A D C

I wonder how to generate lists of edges for all simple paths. Thank you.

[1] 1 4
[2] 1 3 2
Qzhao
  • 57
  • 3

1 Answers1

3

Update

If you just need the edge id, you can use

> lapply(
+   all_simple_paths(demo, "B", "C"),
+   function(x) {
+     get.edge.ids(demo, c(rbind(head(x, -1), x[-1])))
+   }
+ )
[[1]]
[1] 1 4

[[2]]
[1] 1 3 2

Try the code below

lapply(
  all_simple_paths(demo, "B", "C"),
  function(x) {
    E(demo)[get.edge.ids(demo, c(rbind(head(x, -1), x[-1])))]
  }
)

which gives

[[1]]
+ 2/4 edges from d776b98 (vertex names):
[1] B->A A->C

[[2]]
+ 3/4 edges from d776b98 (vertex names):
[1] B->A A->D D->C
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81