如何根据R中每个集群的固定容量制作集群?

问题描述

所以我有一个包含 600 个点、它们的纬度、经度和需求的数据集。 我必须制作集群,以使每个集群的点彼此靠近,并且该集群的总容量不会超过某个限制。

问题的示例数据集:

set.seed(123)
id<- seq(1:600)
lon <- rnorm(600,88.5,0.125)
lat <- rnorm(600,22.4,0.15)
demand <- round(rnorm(600,40,20))

df<- data.frame(id,lon,lat,demand)

我想要的大约是:

The desired output

我得到了什么(集群边界是近似的):

The obtained output

我写的代码

library(tidyverse)
constrained_cluster <- function(df,capacity=170){
  lon_max <- max(df$lon)
  lat_max <- max(df$lat)

#Calculating the distance between an extreme point and all other points

  df$distance<-6377.83*acos(sin(lat_max*p)*sin(df$lat*p) + cos(lat_max*p)*cos(df$lat*p) * cos((lon_max-df$lon)*p))
  df<- df[order(df$distance,decreasing = FALSE),]
  d<-0
  cluster_number<-1
  cluster_list<- c()
  i<-1
#Writing a loop to form the cluster which will fill up the cluster_list accordingly
  while (i <= length(df$distance)){
    d <- d+ df$demand[i]
    if(d<=capacity){
      cluster_list[i] <- cluster_number
      i<- i+1
    }
    else{
      cluster_number <- cluster_number+1
      d <- 0
      i<-i
    }
  }
#Return a dataframe with the list of clusters
  return(cbind(df,as.data.frame(cluster_list)))
}

df_with_cluster<- constrained_cluster(df,capacity = 1000)

我尝试了几种不同的算法,但什么也想不出来。 任何帮助或建议将不胜感激。

解决方法

这样的事情可能会让您入门?

nmax <- 100
num.centers <- 1
km <- kmeans(cbind(df$lat,df$lon),centers = num.centers)
#check if there are no clusters larger than nmax
while (prod(km$size < nmax) == 0) {
  num.centers <- num.centers + 1
  km <- kmeans(cbind(df$lat,centers = num.centers)
}
plot(df$lon,df$lat,col = km$cluster,pch = 20)

enter image description here