从距离矩阵到邻接矩阵

时间:2016-03-09 10:24:38

标签: r distance igraph minimum-spanning-tree adjacency-matrix

我有一个距离1024x1024的矩阵,所有条件之间的距离都是一样的。我想从那开始定义一个图表。所以我定义了一个最小生成树,并在此计算了邻接矩阵。

我的距离矩阵为distMat

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

我的图是包含所有可能弧的图(因为所有两个项之间的距离是有限值)。我需要另一个图表,稀疏:

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

从稀疏图中我可以用以下方法计算邻接矩阵:

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

现在我想以不同方式创建矩阵邻接,传递另一个最小生成树对象。假设我创建了另一个生成树:

spt <- spantree(matrix_of_distances)

如果我这样做:

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

我收到错误:

  

as_adjacency_matrix中的错误(spt,type = c(&#34;两者&#34;,&#34;上&#34;,&#34;下&#34;),   :不是图表对象

同样,我试图从最小生成树生成邻接矩阵。我怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

错误来自于URLUserAllowedCharacterSet()类对象上的使用函数as_adjacency_matrix,当它需要spantree时。

由于您使用的是igraph,因此一个简单的解决方案是使用igraph的函数igraph计算原始“距离图”中的最小生成树。

以下是mst计算最小生成树的方式:

spantree

结果是以下树(require(vegan) data(dune) dis <- vegdist(dune) tr <- spantree(dis)

enter image description here

您只能使用plot(tr, type="t")函数获得相同的结果:

igraph

结果树看起来像这样(library(igraph) g <- graph.adjacency(as.matrix(dis), weighted=TRUE) g_mst <- mst(g) ):

enter image description here

获得plot(g_mst, vertex.color=NA, vertex.size=10, edge.arrow.size=0.5)树后,您已经知道可以将其转换为函数igraph的邻接矩阵:

as_adjacency_matrix