How to complete a graph assigning 0 as weight attribute of new edges

萝らか妹 提交于 2019-12-25 07:48:19

问题


Please consider the following graph

library(igraph)
g <- erdos.renyi.game(100, 2/100)
E(g)$weight <- sample(1:10, ecount(g), replace=TRUE)

I am interested in "completing" the graph by adding all missing edges (as a result each pair of vertices will be connected by an edge) but making sure the new edges are assign E(g)$weight = 0.

Is it possible?


回答1:


This should work.

olde = E(g)                       # saving edges
g[V(g), V(g)] <- TRUE             # adding all possible edges
E(g)$weight <- 0                  # all weights is 0 
E(g)[olde]$weight <- olde$weight  # old weights is equal to old weights  
g <- simplify(g)                  # removing loops

According to the comments, I would like to suggest more robust answer that is based on the extra attribute of edges, please see below and give comments.

ids = E(g)                        # saving old ids
E(g)$oldids = ids                 # assigning to specific edge as extra attribute
olde = E(g)                       # saving edges

g[V(g), V(g)] <- TRUE             # adding all possible edges
E(g)$weight <- 0                  # all weights is 0 

# Now it is more robust, because it matches oldids with the ids of old graph
E(g)[match(ids, oldids)]$weight <- olde$weight[ids]  # old weights is equal to old weights 


来源:https://stackoverflow.com/questions/21619566/how-to-complete-a-graph-assigning-0-as-weight-attribute-of-new-edges

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!