In a previous post I demonstrated how one can assign customers to the nearest warehouse using a well-known clustering algorithm. In this post I will demonstrate how a single warehouse location problem can be approached by applying center of mass calculation in R. The idea is to locate the warehouse in right in the average center of demand, taking into account spatial distribution of customer demand.
Below, I define the center of mass function. It takes into account x and y coordinates. I.e. we simplify the problem by neglecting the vertical z-axis of our spatial location problem. w stands for the weights of the respective coordinates. This could e.g. be the demand by location.
center_of_mass <- function(x,y,w){
c(crossprod(x,w)/sum(w),crossprod(y,w)/sum(w))
}
Next, I create a dataframe representing customer demand. I apply latitude and longitude coordinates. Latitude value range is from -90 to +90. Longitude value range is from -180 to +180. I create 40 customers with random location and demand, somewhere within the coordinate-system.
customer_df <- as.data.frame(matrix(nrow=40,ncol=3))
colnames(customer_df) <- c("lat","long","demand")
customer_df$lat <- runif(n=40,min=-90,max=90)
customer_df$long <- runif(n=40,min=-180,max=180)
customer_df$demand <- sample(x=1:100,size=40,replace=TRUE)
Below I print the header of that dataframe:
head(customer_df)
## lat long demand
## 1 -46.40781 43.13533 4
## 2 -29.06806 98.97764 72
## 3 -75.84997 127.47619 44
## 4 -54.37377 55.16857 66
## 5 71.67371 178.98597 21
## 6 -34.03587 -42.88747 100
Using that dataset I can calculate the center of mass:
center_of_mass(customer_df$lat,customer_df$long,customer_df$demand)
## [1] -2.80068 12.49750
To assess this result, I plot the customer demand using ggplot2:
library(ggplot2)
joint_df <- rbind(customer_df,c(center_of_mass(customer_df$lat,customer_df$long,customer_df$demand),50))
joint_df$type <- c(rep(x="customer",times=40),"warehouse")
ggplot(data=joint_df) + geom_point(mapping=aes(x=lat,y=long,size=demand,color=type))

The center of mass method can be well combined with heatmap visualisation of spatial customer demand distribution. For this, you can read my blog post on how to create heatmaps in R, using the Leaflet package: Leaflet heatmaps in R
I also use other packages to visualize spatial distribution of customer demand, including deckgl: Using deckgl in R for spatial data visualisation
3 thoughts on “Single warehouse problem: Locating warehouse at center of mass (using R)”