3

input:

data.frame(from = c(NA, 2, 4, 5, 8, 8, 1),
           to   = c(1, 3, 7, 6, 9, 10, 11))


 from to
   NA  1
    2  3
    4  7
    5  6
    8  9
    8 10
    1 11

I want to know how to use igraph to select a starting vertex, and get all the continuously connected vertices.

example

select(2) -> c(2, 3)
select(4) -> c(4, 7)
select(1) -> c(1, 11)
select(8) -> c(8, 9, 10)

The idea is: I don't know the ending vertex, I just know the starting point and I want to return the continuous path starting from this point

  • Would something like this - http://stackoverflow.com/questions/12135971/identify-groups-of-linked-episodes-which-chain-together - be a good starting point that you could match back to? – thelatemail Apr 04 '16 at 23:02
  • Thank you brother, but not exactly what I'm looking for – Hisham Hussein Apr 04 '16 at 23:09
  • maybe`?all_simple_paths` or `?ego` – user20650 Apr 04 '16 at 23:22
  • That's quite close [user20650](http://stackoverflow.com/users/2250190/user20650) but, there's a catch. it only returns the vertices that were visited one time. In my example: `all_simple_paths(df, from = 8)` would return an empty list, because 8 is visited twice – Hisham Hussein Apr 04 '16 at 23:26
  • Use quotes... `all_simple_paths(g, "8")`. All together: `ego(g, length(V(g)), as.character(c(1,2,4,8)))`, or `lapply(as.character(c(1,2,4,8)) , function(x) all_simple_paths(g, from=x))` get you v. close to your expected outcome. Shouldnt be difficult to tweak. – user20650 Apr 04 '16 at 23:30
  • 1
    Thanks bro [user20650](http://stackoverflow.com/users/2250190/user20650). That was helpful – Hisham Hussein Apr 05 '16 at 00:12
  • @HishamHussein; It would be good to write up an answer, if you have managed to solve your question – user20650 Apr 05 '16 at 21:05
  • @user20650. The answer you already provided brother. I just used your answer. If I wrote an answer, it would be a duplicate of yours, so no need for it. – Hisham Hussein Apr 06 '16 at 16:40
  • okay, ill write it up then, so then Q can be marked as answered – user20650 Apr 06 '16 at 16:47

1 Answers1

3

You can use either ego or all_simple_paths to find the connected nodes, which give slightly different output, depending on your need.(ego gives the neighbours up to a specified depth in one string, and all_simple_paths separates the nodes by path direction)

#Your example

library(igraph)

g <- graph_from_data_frame(data.frame(from = c(NA, 2, 4, 5, 8, 8, 1),
           to   = c(1, 3, 7, 6, 9, 10, 11)))

 all_simple_paths(g, "2")
# [[1]]
# + 2/12 vertices, named:
# [1] 2 3

 ego(g, length(V(g)), "2")
# [[1]]
# + 2/12 vertices, named:
# [1] 2 3

All together:

ego(g, length(V(g)), as.character(c(1,2,4,8)))

or

lapply(as.character(c(1,2,4,8)) , function(x) all_simple_paths(g, from=x))
user20650
  • 24,654
  • 5
  • 56
  • 91