定义重心(聚类任务)

时间:2017-05-21 00:06:28

标签: r tree cluster-computing gravity

大家好我已经完成了这个代码,它将向我展示欧盟一些城市的最小生成树。其实我想知道是否有计算重心的功能。考虑到距离和需求,我必须在这些城市之间选择三个集群。这是我的代码:

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"))

基本上,如果您将运行此代码,您的输出将是这些特定城市之间的最小连接。我也应该写出每个城市的需求: 曼彻斯特75蒂尔伯里220 巴黎250马德里150 米兰100慕尼黑125 雷克雅未克25索非亚47 法兰克福111布拉格31 Florence 45 Barcelona 80 如何根据这些需求和距离再次找到最好的三个群集?哪三个最有价值的配送中心?

感谢您的帮助

0 个答案:

没有答案