Wimpel
Wimpel

Reputation: 27732

find all paths in a graph though a node/vertex

Ive got a directed igraph:

library( igraph )
links <- data.frame( from = c(1,1, 2,2,3, 3,3,4,6,7,7, 8),
                     to =   c(2,10,3,4,12,4,8,5,7,3,11,9) )
nodes <- data.frame( name = 1:12 )
net <- graph_from_data_frame( d = links, vertices = nodes, directed = TRUE ) 
plot(net)

enter image description here

What i want is:

  1. get a subset of the graph, of all nodes that are within one step of node 3 (in and out)
  2. get a list of all paths in the subset, that go through node 3

For step 1, I can do:

ego.list <- make_ego_graph( net, order = 1, nodes = 3, mode = "all")
desired_subset <- NULL
for (i in seq_along(ego.list) ){
  x <- ego.list[[i]]
  desired_subset <- graph.union( desired_subset, x )
}
plot(desired_subset)

enter image description here

But now I'm stuck.. What i want, is to find all paths in the entire (directed) subset, that go through node 3, so:

All I've found so far is to get a list of paths from one node to another node. But I want to get a list of all paths through a certain node.
Any ideas?

Upvotes: 1

Views: 670

Answers (1)

Wimpel
Wimpel

Reputation: 27732

found a solution!

using All paths in directed tree graph from root to leaves in igraph R I came to the following code:

#for shorter code
g <- desired_subset
# find entrynodes (nothing goes in) and exit_nodes (nothing goes out)
exit_nodes  <- which( degree(g, v = V(g), mode = "out" ) == 0 )
entry_nodes <- which( degree(g, v = V(g), mode = "in" ) == 0)
# find all paths from entry to exit nodes
paths= lapply( entry_nodes, function(x) all_simple_paths(g, from = x, to = exit_nodes))
named_paths= lapply(unlist(paths, recursive=FALSE), function(x) V(g)[x])
#filter out all paths that do not contain node 3
answer <- named_paths[ unlist( lapply( named_paths, function(x) 3 %in% names(x) ) ) ]
#put in a data.table
as.data.table(data.table::transpose( lapply(answer, names) ) )

#    V1 V2 V3
# 1:  2  3  4
# 2:  2  3  8
# 3:  2  3 12
# 4:  7  3  4
# 5:  7  3  8
# 6:  7  3 12

Upvotes: 1

Related Questions