Search code examples
rcluster-analysisk-means

Cluster Analysis in R: Elbow Method in K-means


I'm implementing the elbow method to my data set using the R package fviz_nbclust. This method will calculate the total within sum square of each cluster by varying K from 1.....k. For example the elbow method suggest K=2. Say we have here two different results for K-means alone. Is there a way to find out which wss did the elbow method calculated? Is there a possible way to view which K-means result the elbow method used in clustered using K=2?

enter image description here


Solution

  • There might be more elegant methods but you could simply add out-of-scope assignment to your cluster function, e.g.:

    l <- list()
    f <- function(...) {
      km <- kmeans(...)
      l[[nrow(km$centers)]] <<- km
      km
    }
    
    fviz_nbclust(df, f, method = "wss", k.max = 10)
    

    Then simply index l[[optimal nr of clusters]] to retrieve the model