R iGraph: How to get weighted adjacency matrix fro

2020-04-21 03:19发布

问题:

While there are some questions dealing with creating a graph from an adjacency matrix, I haven't found much about extracting the weighted adjacency matrix from a weighted graph.

Say I have the following graph:

library(igraph)
nodes <- data.frame(name=c("a","b", "c", "d", "f", "g"))

col1 <- c("a", "g", "f","f", "d","c")
col2 <- c("b", "f","c","d","a","a")
weight <- c(1,4,2,6,2,3)
edges <- cbind.data.frame(col1,col2,weight)

g <- graph.data.frame(edges, directed=F, vertices=nodes)
E(g)$weight <- weight

How do I get the weighted adjacency matrix of graph g?

回答1:

It appears there are actually quite a few ways to do this. Perhaps obvious, a first way to do it is to look carefully at the documentation of as_adjacency_matrix() and using the attr option:

as_adjacency_matrix(g,attr = "weight",sparse = T)

6 x 6 sparse Matrix of class "dgCMatrix"
  a b c d f g
a . 1 3 2 . .
b 1 . . . . .
c 3 . . . 2 .
d 2 . . . 6 .
f . . 2 6 . 4
g . . . . 4 .

But one can also type

get.adjacency(g,attr = "weight",sparse = T)

Or just

g[]

6 x 6 sparse Matrix of class "dgCMatrix"
  a b c d f g
a . 1 3 2 . .
b 1 . . . . .
c 3 . . . 2 .
d 2 . . . 6 .
f . . 2 6 . 4
g . . . . 4 .

Even if I'm not sure of the scope of validity of this last option.