Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting Directed igraph

I'm working with a directed network in igraph. Here's some code to generate such a network:

# example graph
# install.packages(c("igraph"), dependencies = TRUE)
library(igraph)
set.seed(1)
g <- erdos.renyi.game(20, 1/20,directed=TRUE,loops=FALSE)
V(g)$name <- letters[1:20]
par(mar=rep(0,4))
plot(g)

I would like to extract subsets of this network that include an arbitrary vertex and all edges and vertices that direct to this vertex, regardless of the degree or distance of that connection.

Here's a photoshopped example of what I would like to extract, using vertex "E" in this case. I would like to extract a network that includes all vertices labeled in blue and connected edges. Subset of network graph

like image 365
Electioneer Avatar asked Jan 02 '23 22:01

Electioneer


2 Answers

Besides what @42-, I think distance can also be used.

> d = distances(g, to='e', mode='out')
> V(g)[which(!is.infinite(d) & d >0)]
+ 4/20 vertices, named:
[1] a n r t

Briefly, the code within the brackets returns the indices of vertices that has nonzero and finite distances from e to others.

like image 143
Zhiya Avatar answered Jan 05 '23 14:01

Zhiya


It seems that the edge_connectivity funciton is a good candidate for this task. It has source and target parameters that consider the directedness of the edges:

 sapply(V(g) , function(v) if( v != 5){edge_connectivity(g, source=v, target=5)} else NA )
 a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p  q  r  s  t 
 1  0  0  0 NA  0  0  0  0  0  0  0  0  1  0  0  0  1  0  1 
 # set the retruned vector to the value named `e_con`

 #then select the vertices
 V(g)[ which(e_con >0)]
+ 4/20 vertices, named, from ba45ff0:
[1] a n r t

It's possible to recover a graph object with that list:

small_g <- delete_vertices( g, !V(g) %in% c(5, V(g)[ which(econ >0)] ))

plot( small_g)

enter image description here

And you asked for the edge list:

edges(small_g)
[[1]]
IGRAPH 11d63f6 DN-- 5 4 -- Erdos renyi (gnp) graph
+ attr: name (g/c), type (g/c), loops (g/l), p (g/n), name (v/c)
+ edges from 11d63f6 (vertex names):
[1] n->a t->a a->e r->e
like image 20
IRTFM Avatar answered Jan 05 '23 14:01

IRTFM