简体   繁体   中英

Assigning edge weight to an igraph object in R

I have a co-occurrence matrix that I want to convert to an igraph object. The matrix has three columns- node1 , node2 and freq .

I have created the graph using the graph_from_edgelist command.

g <- graph_from_edgelist(as.matrix(coOccurDf[1:n,1:2]), directed=F)

I now need to assign weights to the edges. I've tried to use two functions, which both seem to do the same job, but to no avail.

set.edge.attribute(g, "weight", index=E(g), coOccurDf[1:n,]$freq)

and

set_edge_attr(g, "weight", index=E(g), coOccurDf[1:n,]$freq)

Neither of these two commands throws an error, but when I try to see the weights using

E(g)$weight

It just displays NULL .

Any help would be appreciated.

You can return the weights of an igraph object as follows:

edge.attributes(g)$weight

E(g)$weight

You can set weights of an igraph object by assigning to either of these:

edge.attributes(g)$weight <- coOccurDf[1:n,]$freq

E(g)$weight <- coOccurDf[1:n,]$freq

To use the set.edge.attribute function it returns a new graph with weights assigned. To assign it to an object g rather than print the weighted graph to the console:

g <- set.edge.attribute(g, "weight", index=E(g), coOccurDf[1:n,]$freq)

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