R iGraph:如何从图中获取加权邻接矩阵?

R iGraph: How to get weighted adjacency matrix from a graph?

虽然有一些关于从邻接矩阵创建图形的问题,但我没有找到太多关于提取 weighted来自加权图的邻接矩阵。

假设我有下图:

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

如何得到图g的加权邻接矩阵?

看起来实际上有很多方法可以做到这一点。 也许很明显,第一种方法是仔细查看 as_adjacency_matrix()documentation 并使用 attr 选项:

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 .

但也可以输入

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

或者只是

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 .

即使我不确定最后一个选项的有效性范围。