问题
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