Minimum spaning tree with Kruskal' algorithm

纵饮孤独 提交于 2021-02-07 09:04:18

问题


How i can calculate im R(3.0.0 - Linux x32) minimum spanning tree with Kruskal's algorithm?

I create an weighted full graph with igraph (0.6.5) library as folws:

set.seed(1234567890)
g <- graph.full(n = 20)
E(g)$weight <- round(runif(ecount(g)), 2) * 100

And i am able to calcutae the minimum spaning tree with Prim (igraph)

mstPrim <- minimum.spanning.tree(g, algorithm = "prim")

But unfortunaly doesn't in "igraph" Kruskal's algorithm implemented.

I can represent my genereted graph as a data.frame:

edgeMatrix <- data.frame(cbind(get.edgelist(g), E(g)$weight))
names(edgeMatrix) <- c("from", "to", "weight")

Is there a simple way to calculate mst with Kruskal's alogithm in R?


回答1:


A small workaround with RBGL package:

#convert with graph packagege to BAM class of graph an calculate mst
mstKruskalBAM <- mstree.kruskal(graphBAM(edgeMatrix))
#build new data frame with resut
mstKruskalDF <- data.frame(cbind(t(mstKruskalBAM$edgeList),
                                 t(mstKruskalBAM$weight)))
#convert back to igraph package
mstKruskal <- graph.data.frame(mstKruskalDF, directed=FALSE)

Now is it possible to plot and compare both aloriph with defining a layout algorithm like this:

plot(mstPrim, layout = layout.kamada.kawai, edge.label = E(mstPrim)$weight)
plot(mstKruskal, layout = layout.kamada.kawai, edge.label = mstKruskal$weight)



回答2:


I think mst function in ape package implements this.

http://cran.r-project.org/web/packages/ape/ape.pdf



来源:https://stackoverflow.com/questions/16605825/minimum-spaning-tree-with-kruskal-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!