在igraph(R)中添加边和顶点而不重复

时间:2015-01-06 12:50:07

标签: r igraph

尝试创建一个空图并添加边和顶点。

library(igraph)
g<-graph(edges =,NULL,n=NULL,directed =FALSE)
g=g+vertices("5","6")
g=g+edge("5","6")

However when I try to do
g=g+vertices("5")

它复制节点“5”。

如何保持唯一的节点和顶点。 所以g = g +顶点(“5”)不会添加任何东西。

1 个答案:

答案 0 :(得分:3)

我不认为igraph中有一些内置函数,但您可以轻松创建一个而不是g + vertices(...)

addVertIfNotPresent <- function(g, ...){
  names2add <- setdiff(list(...),V(g)$name)
  v2add <- do.call(vertices,names2add)
  g <- g + v2add
}

使用示例:

library(igraph)

g <- graph(edges=NULL,n=NULL,directed=FALSE)
g = addVertIfNotPresent(g,"5","6")
g = g + edge("5","6")

# "5","6" won't be added and "7" will be added just once
g=addVertIfNotPresent(g,"5","6","7","7") 

plot(g)

enter image description here