问题
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