Bipa
Bipa

Reputation: 309

Adding edge weights from dataframe with igraph in R

I created a graph object

ig <- graph(df$ig)

And would like to be able to plot the graph with weighted edges according to the network matrix

ig[]

The ig[] is not weighted, how do I add the weights directly from the network matrix so I can access it with E(ig)$weight?

Upvotes: 4

Views: 6261

Answers (2)

Bipa
Bipa

Reputation: 309

The following answer may help ([igraph] capturing edge weights in g <- graph.data.frame?):

If the weights are not given in the data frame explicitly but you simply want to use the number of email exchanges as weights, you can do this:

> df <- data.frame(from=c("a", "b", "a"), to=c("b", "a", "b"))
> g <- graph.data.frame(df)
> E(g)$weight <- 1
> g <- simplify(g, edge.attr.comb="sum")

I have then added the following line to be able to plot the width in the graph.

 E(themes_graph)$width <-E(themes_graph)$weight/15

Upvotes: 1

Panos Kalatzantonakis
Panos Kalatzantonakis

Reputation: 12673

You can weight to your graph like this:

Example: gg3 <- graph.ring(10)

 [1,] . 1 . . . . . . . 1
 [2,] 1 . 1 . . . . . . .
 [3,] . 1 . 1 . . . . . .
 [4,] . . 1 . 1 . . . . .
 [5,] . . . 1 . 1 . . . .
 [6,] . . . . 1 . 1 . . .
 [7,] . . . . . 1 . 1 . .
 [8,] . . . . . . 1 . 1 .
 [9,] . . . . . . . 1 . 1
[10,] 1 . . . . . . . 1 .

E(gg3)$weight <- 15

 [1,]  . 15  .  .  .  .  .  .  . 15
 [2,] 15  . 15  .  .  .  .  .  .  .
 [3,]  . 15  . 15  .  .  .  .  .  .
 [4,]  .  . 15  . 15  .  .  .  .  .
 [5,]  .  .  . 15  . 15  .  .  .  .
 [6,]  .  .  .  . 15  . 15  .  .  .
 [7,]  .  .  .  .  . 15  . 15  .  .
 [8,]  .  .  .  .  .  . 15  . 15  .
 [9,]  .  .  .  .  .  .  . 15  . 15
[10,] 15  .  .  .  .  .  .  . 15  .

or

E(gg3)$weight <- c(20,10)

 [1,]  . 20  .  .  .  .  .  .  . 10
 [2,] 20  . 10  .  .  .  .  .  .  .
 [3,]  . 10  . 20  .  .  .  .  .  .
 [4,]  .  . 20  . 10  .  .  .  .  .
 [5,]  .  .  . 10  . 20  .  .  .  .
 [6,]  .  .  .  . 20  . 10  .  .  .
 [7,]  .  .  .  .  . 10  . 20  .  .
 [8,]  .  .  .  .  .  . 20  . 10  .
 [9,]  .  .  .  .  .  .  . 10  . 20
[10,] 10  .  .  .  .  .  .  . 20  .

Check this out: Using edge-lists with associated edge values to create a weighted network.

Upvotes: 2

Related Questions