简体   繁体   中英

adding edges and vertices without duplication in igraph (R)

Tried to create an empty graph and add edges and vertices.

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

it duplicates the node "5".

How to keep nodes and vertices which to be unique. so g=g+vertices("5") won't add anything.

I don't think there's some built-in function in igraph , however you can easily create one to use instead of g + vertices(...) :

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

Example usage :

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)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM