子集定向igraph

时间:2018-01-18 17:46:06

标签: r igraph network-analysis

我正在使用igraph中的定向网络。以下是生成此类网络的一些代码:

# 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)

我想提取此网络的子集,其中包含任意顶点以及指向此顶点的所有边和顶点,无论该连接的程度或距离如何。

这是一个我想要提取的示例的示例,在这种情况下使用顶点“E”。我想提取一个网络,其中包括标记为蓝色和连接边的所有顶点。 Subset of network graph

4 个答案:

答案 0 :(得分:3)

除了@ 42-,我认为distance也可以使用。

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

简而言之,括号内的代码返回从e到其他距离的非零距离和有限距离的顶点索引。

答案 1 :(得分:2)

似乎edge_connectivity函数是此任务的一个很好的候选者。它有sourcetarget参数,可以考虑边缘的方向性:

 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

可以使用该列表恢复图形对象:

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

plot( small_g)

enter image description here

你问边缘清单:

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

答案 2 :(得分:1)

您可以使用make_ego_graph获取特定节点的邻域图。将顺序设置为顶点数(或n-1)以允许遍历完整图形。

make_ego_graph(g, order=length(V(g)), nodes="e", mode="in")

enter image description here

答案 3 :(得分:0)

我认为这里给出的所有三个答案都很有用,但@Zhiya的解决方案是我最终使用的解决方案(它似乎是计算速度最快的方法)。

那就是说,我最终使用了来自@ 42-的元素,因为我想要的输出是一个子集网络。以下是解决此问题的更改:

d = distances(g, to='e', mode='out')
vertices.to.delete <- row.names(d)[which(is.infinite(d))]
g1 <- igraph::delete.vertices(g, vertices.to.delete)