简体   繁体   中英

From a matrix of distances to a matrix of adjacency

I have a matrix of distances 1024x1024 with all the couple of distances between all the terms. I want to define a graph starting from that. So I defined a minimum spanning tree and I computed the matrix of adjacency on that.

My matrix of distances is distMat .

matrix_of_distances <- as.matrix(distMat)
myGraph <- graph.adjacency(matrix_of_distances, weighted=TRUE)

My graph is a graph with all the possible arcs (because the distances between all the couple of terms are a finite value). I need another graph, sparser:

mst <- as.undirected(minimum.spanning.tree(myGraph))

From that sparse graph I can compute the matrix of adjacency with:

adjacency <- as_adjacency_matrix(mst, type = c("both", "upper", "lower"), attr = NULL, edges = FALSE, names = TRUE, sparse =igraph_opt("sparsematrices"))

Now I want to create the matrix adjacency differently, passing another minimum spanning tree object. Suppose I have created another spanning tree:

spt <- spantree(matrix_of_distances)

If I do:

adjacency <- as_adjacency_matrix(spt, type = c("both", "upper", "lower"), attr = NULL, edges = FALSE, names = TRUE, sparse =igraph_opt("sparsematrices"))

I get the error:

Error in as_adjacency_matrix(spt, type = c("both", "upper", "lower"), : Not a graph object

Again, I'm trying to generate a matrix of adjacency from a minimum spanning tree. How can I solve that?

The error comes from your using function as_adjacency_matrix on an object of class spantree when it expects an igraph .

Since you are using igraph , one simple solution would be to compute the minimum spanning tree from your original "distance graph" with igraph 's function mst .

Here is how spantree computes the minimum spanning tree:

require(vegan)
data(dune)
dis <- vegdist(dune)
tr <- spantree(dis)

The result is the following tree ( plot(tr, type="t") )

在此输入图像描述 :

You could get the same result only with igraph functions:

library(igraph)
g  <- graph.adjacency(as.matrix(dis), weighted=TRUE)
g_mst <- mst(g)

And the resulting tree looks like this ( plot(g_mst, vertex.color=NA, vertex.size=10, edge.arrow.size=0.5) ):

在此输入图像描述

Once you have your igraph tree, you already know that you can transform it into an adjacency matrix with function as_adjacency_matrix :

A <- as_adjacency_matrix(mst)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM