One way to determine this is by using an automated method known as the `elbow` method in which you plot the total within clusters sum of squares for all values within a range, and look at where an `elbow` method develops in the plot:

#elbow method set.seed(1020) # Compute and plot wss for k = 3 to k = 15 df <- sapply(3:15,function(k){kmeans(y,k)$tot.withinss}) plot(3:15, df,type='b',xlab="# of clusters",ylab="Total Within Clusters SS")

In the following plot, you might see two elbows, one at 5-6 cluster, and one at 8-9. We will assume for now that five is the optimal number, only because there is an elbow in that area, and the names given to the clusters will be easier to explain: