Reputation: 2072
I would like to obtain a subgraph from a graph, composed of all the vertex with incident edges starting from some vertices, and following the edges until there are no more incident edges. With the following code I only get the first neighbours
g <- graph_from_literal( 1 -+ 4 -+ 5 -+ 8,2 -+ 5 , 3-+6-+7, 4+-3, 4-+8, 5 -+9, simplify = FALSE)
adjacent_vertices(g, V(g)[c("7","9")], mode="in")
I know that I should make some kind of loop but adjacent_vertices
returns a list and I can't figure out how to make it.
For this example, the result should be
graph_from_literal( 1 -+ 4 -+ 5 ,2 -+ 5 , 3-+6-+7, 4+-3, 5 -+9, simplify = FALSE)
Upvotes: 1
Views: 387
Reputation: 25864
make_ego_graph
can be used to find subgraphs in the neighbourhood of specific nodes.
You can search through the full graph by setting the order
parameter in
the function make_ego_graph
.
Example
library(igraph)
# Your graph
g = graph_from_literal( 1 -+ 4 -+ 5 -+ 8, 2 -+ 5 , 3-+6-+7, 4+-3, 4-+8, 5 -+9,
simplify = FALSE)
# Set the order equal to the number of nodes in the graph
sg = make_ego_graph(g, nodes = V(g)[c("7","9")], order=length(V(g)), mode="in")
# This returns two subgraphs as node 3 has no inward edges and so the graph 3->6->7
# is unconnected to the other nodes. You can join the subgraphs by using
do.call(union, sg)
Upvotes: 1