使用Igraph中的顶点标签删除边

时间:2018-03-02 21:13:17

标签: r graph igraph vertices edges

我对R很新。我有一个igraph图形对象,我随机标记了顶点TRUE或FALSE。有没有办法删除两个TRUE标记顶点或两个FALSE标记顶点之间的边?

这是我的代码:

g <- read_graph("grph.graphml", format = c("graphml"))
num_of_edges <- gorder(g)
random_list <- sample(c(TRUE,FALSE), num_of_vertices, TRUE) 
V(g)$label <- random_list

1 个答案:

答案 0 :(得分:2)

您的代码是指文件&#34; grph.graphml&#34;我们没有,所以我不能用你的例子。相反,我将使用随机图来说明。

## Generate random graph
library(igraph)
set.seed(1234)
g = erdos.renyi.game(15, 0.2)

## Your code to generate labels
random_list <- sample(c(TRUE,FALSE), gorder(g), TRUE) 
V(g)$label <- random_list

您可以编写一个小函数来测试边的末端是否具有相同的标签并将其应用于所有边。然后删除两端相同的那些。

SameLabel = function(e) {
    V(g)[ends(g, e)[1]]$label == V(g)[ends(g, e)[2]]$label }
g2 = delete_edges(g, which(sapply(E(g), SameLabel)))

您可以通过绘图来检查它是否做得对。

set.seed(1066)
LO = layout_with_fr(g)
par(mfrow=c(1,2), mar=c(1,1,1,1))
plot(g, layout=LO, frame=TRUE)
plot(g2, layout=LO, frame=TRUE)

reduced graph

其中一些看起来不对,因为远程节点之间的链接落后于相反类型的其他节点。

相关问题