R中的igraph是否可以删除不满足某些条件的子图?

Is it possible with igraph in R to delete subgraphs that do not meet certain conditions?

我想创建一个包含所有 clusters/groups 的子图,该子图由至少一个红色和一个绿色节点组成。但是,集群仍应包含灰色节点,以防特定集群中也有灰色节点。

library (igraph)

#### Random graph #####
set.seed(123) #reproduction
g <- erdos.renyi.game(75,1/75, directed =  F, loops = F)

#### simple random sample from graph object #####
set.seed(123) #reproduction
smpl1 <- sample(1:vcount(g),20)
smpl2 <- sample(1:vcount(g),20)

##### add colours #####
V(g)$color = "green"
V(g)[smpl1]$color = "red"
V(g)[smpl2]$color = "grey"

set.seed(123) #reproduction
plot(g,
     vertex.label.color = "Black",
     vertex.size = 10,
     layout = layout.fruchterman.reingold(g))

使用上面的代码,预期输出是一个图,其中包括至少有一个绿色节点和一个红色节点的剩余(四个)集群。

当您说 "I want to create a subgraph that includes all the clusters/groups that consists out of at least one red and one green node." 时,我假设您指的是连通分量。所以重申一下,你想要由所有灰色节点和至少包含一个红色和一个绿色节点的连接组件中的那些节点导出的子图。

做到这一点并不难。首先计算连通分量。列出要保留的节点并生成子图。

CG = components(g)
KeepNodes = which(V(g)$color == "grey")
for(i in 1:max(CG$membership)) {
    CompNodes = which(CG$membership == i)
    if(any(V(g)$color[CompNodes] == "green") + 
        any(V(g)$color[CompNodes] == "red") == 2) {
        KeepNodes = union(KeepNodes, CompNodes) }
}
SubGraph = induced_subgraph(g, KeepNodes)
plot(SubGraph)