Hi everyone I got this code already done that will show me the Minimal Spanning Tree of some cities in EU. Actually i would like to know if there is a function to calculate the centre of gravity. I have to choose three clusters between these cities considering their distances and demand. This is my code:
library(ggmap)
library(igraph)
lonlat <- read.table(textConnection(
"lon, lat
2.3488000,48.8534100
-2.2374300,53.4809500
-3.7025600,40.4165000
9.1895100,45.4642700
11.575490,48.1374300
-21.895410,64.1354800
23.324150,42.6975100
8.6841700,50.1155200
14.4207600,50.0880400
0.3456012,51.461045
11.2462600,43.7792500
2.1589900,41.3887900
"),header=TRUE,strip.white = TRUE, sep=",")
nname = c("Paris","Manchester","Madrid","Milan","Munich",
"Reykjavik","Sofia","Frankfurt",
"Praga","Tilbury", "Florence", "Barcelona")
v = data.frame(
ids = 1:12,
name = nname,
x = lonlat$lon,
y = lonlat$lat)
qmap('Europe',zoom=3)+geom_point(data = v, aes(x = x, y = y),color="red")
qmap('Europe',zoom=4)+geom_point(data = v, aes(x = x, y = y),color="red")
library(geosphere)
D <- distm(lonlat, lonlat, fun=distVincentyEllipsoid) # in meters
mat2list <- function(D) {
n = dim(D)[1]
k <- 1
e <- matrix(ncol = 3,nrow = n*(n-1)/2)
for (i in 1:(n-1)) {
for (j in (i+1):n) {
e[k,] = c(i,j,D[i,j])
k<-k+1
}
}
return(e)
}
eD = mat2list(D/1000)
net <- graph.data.frame(eD[,1:2],directed = FALSE, vertices = v)
E(net)$weight <- eD[,3] # Important use edge weight rather than net$weight
mst <- minimum.spanning.tree(net)
par(mfrow=c(1,2), mar=c(0,1,0.75,0))
plot(net,vertex.label=NA)
plot(mst, vertex.shape="none",edge.label=round(E(mst)$weight))
mst2lines <- function(mst,lonlat) {
me = get.edges(mst,1:ecount(mst))
R = data.frame(lon=NULL,lat=NULL,group=NULL)
for (k in 1:ecount(mst)) {
A = lonlat[me[k,],]
A$group = k
R <- rbind(R,A)
}
rownames(R) <- NULL
return(R)
}
R = mst2lines(mst, lonlat)
map <- qmap('Europe',zoom=3, maptype='hybrid')
range <- (apply(lonlat,2,max) - apply(lonlat,2,min))*.10
xlimits = c(min(lonlat$lon)-range[1],max(lonlat$lon)+range[1])
ylimits = c(min(lonlat$lat)-range[2],max(lonlat$lat)+range[2])
library(ggrepel)
map + coord_map(xlim = xlimits, ylim = ylimits)+
geom_path(aes(x = lon, y = lat, group=group), data = R, colour = 'pink', size = 1)+
geom_point(data = v, aes(x = x, y = y), color="white", size=10, alpha=0.5)+
geom_label_repel(data = v, aes(x = x, y = y, label=name),size=4,
point.padding = unit(0.5, "lines"))
Basically if you will run this code your output will be the minimal connection between these particular cities. I also should write the demand per each city: Manchester 75 Tilbury 220 Paris 250 Madrid 150 Milan 100 Munich 125 Reykjavik 25 Sofia 47 Frankfurt 111 Prague 31 Florence 45 Barcelona 80 How can i find the best three cluster depending from these demand and distances again ?? Which are the three most valuable distribution centre ?
Thanks for your help