Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: Return list of edges of all simple paths

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1] 1 4
[2] 1 3 2

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading