微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何根据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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。