Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R igraph - Convert a weighted adjacency matrix into weighted edgelist

Tags:

r

matrix

igraph

I have a nxm adjacency matrix, where (i,j) represent the score of association between i and j. I need to convert this into the following format like : i j <score1>

using R' igraph package and output it into a text file.

I can derive the edgelist, but its showing up without the weights. I used the following code:

library(igraph) g <- graph.adjacency(myAdjacencymatrix) get.edgelist(g)

However, it does not show the weights.

like image 308
Benny Avatar asked Jul 14 '14 18:07

Benny


1 Answers

library(igraph)
set.seed(1)                # for reproducible example
myAdjacencyMatrix <- matrix(runif(400),nc=20,nr=20)

g  <- graph.adjacency(myAdjacencyMatrix,weighted=TRUE)
df <- get.data.frame(g)
head(df)
#   from to    weight
# 1    1  1 0.2655087
# 2    1  2 0.9347052
# 3    1  3 0.8209463
# 4    1  4 0.9128759
# 5    1  5 0.4346595
# 6    1  6 0.6547239

You need to use weighted=TRUE in the call to graph.adjacency(...) to have weights assigned to the edges. Then, get.data.frame(...) will return a data frame of the edges with all edge attributes by default. You can use the what=... argument to return, e.g., the vertex list with attributes.

In future: provide an example, rather than forcing us to create one for you!!!

like image 80
jlhoward Avatar answered Oct 08 '22 20:10

jlhoward