R语言iGraph:如何从图中提取加权邻接矩阵?
Great question—you’re totally right that most resources focus on building graphs from adjacency matrices, but pulling the weighted version back out can feel overlooked if you don’t know the right tool. Let’s walk through this with your exact example graph.
First, let’s confirm we’re working with the same setup (I’ll reuse your code for context):
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
The Solution: Use as_adjacency_matrix() with the Weight Attribute
igraph has a built-in function as_adjacency_matrix() that’s made for this—you just need to specify that you want to use the weight attribute for the edge values.
Here’s the code to get your weighted matrix:
# Extract weighted adjacency matrix (returns a sparse matrix by default) weighted_adj_sparse <- as_adjacency_matrix(g, attr = "weight") # Convert to a dense, easy-to-read matrix if needed weighted_adj_dense <- as.matrix(as_adjacency_matrix(g, attr = "weight"))
What the Output Looks Like
For your undirected graph, the dense matrix will be symmetric (each edge’s weight appears in both (i,j) and (j,i) positions):
a b c d f g a 0 1 3 2 0 0 b 1 0 0 0 0 0 c 3 0 0 0 2 0 d 2 0 0 0 6 0 f 0 0 2 6 0 4 g 0 0 0 0 4 0
Quick Notes:
- Sparse matrices are great for large graphs (they save memory by only storing non-zero values), but converting to dense with
as.matrix()is helpful for small graphs like yours to inspect easily. - If your graph were directed, the matrix would be asymmetric, reflecting the direction of each edge’s weight.
That’s all there is to it—this will give you the exact weighted adjacency matrix you’re looking for.
内容的提问来源于stack exchange,提问作者Nonancourt

