I need to obtain a subgraph of the seed nodes (the input list of nodes; file.txt) and their first interactors (neighbours) from a graph (g) using igraph. Unfortunately, I am
There is a built-in igraph function for that. Try make_ego_graph():
library(igraph)
graph <- make_ring(7)
V(graph)$name <- c("A", "B", "C", "D", "E", "F", "G")
# Get the list of induced subgraphs
subgraph <- make_ego_graph(graph, order=1, c("A", "D", "F"))
I'm not sure to have completely understood your problem, so I have created a (hopefully) self-explanatory example:
# for example reproducibility
set.seed(123)
# create a fake undirected graph
D <- read.table(
sep=',',
header=T,
text=
'from,to
A,B
A,C
D,E
F,G
H,I')
g1 <- graph.data.frame(D,directed=F)
plot(g1)
# we want a sub-network containing the floowing nodes:
subv <- c('A','B','H')
# first method:
# create a sub-network composed by ONLY the nodes in subv and the edges
# between them
g2 <- induced.subgraph(graph=g1,vids=subv)
plot(g2)
# second method:
# create a sub-network composed by the nodes in subv and, if some of them is
# connected to other nodes (even if not in subv), take also them
# (and of course include all the edges among this bunch of nodes).
sg1 <- decompose.graph(g1,mode="weak")
neighverts <- unique(unlist(sapply(sg1,FUN=function(s){if(any(V(s)$name %in% subv)) V(s)$name else NULL})))
g3 <- induced.subgraph(graph=g1,vids=neighverts)
plot(g3)
Graph g1 :
Graph g2 :
Graph g3 :