Reputation: 43
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
Upvotes: 3
Views: 809
Reputation: 25914
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))
Upvotes: 3