user3234810
user3234810

Reputation: 482

How to re-name kmeans clusters by numerically sorted centres

I am trying to numerically set the cluster values of kmeans() output in R.

I am asking for help manually resetting kmeans cluster id's based on a numerically sorted km$centres. So that cluster 1 represents numerically high values, cluster 2 the next highest and cluster 3 the lowest.

#Quick DF 
id   <- seq(1, 100, by=1)
nums <- runif(100, min=0, max=10)
df   <- data.frame( id , nums )

#Kmeans 
km <- kmeans( df$nums , 3 , nstart = 20 )
km$centers 

Upvotes: 0

Views: 70

Answers (1)

steveLangsford
steveLangsford

Reputation: 646

Do you mean

km$cluster <- sapply(km$cluster,function(x){rank(-km$centers)[x]})

Upvotes: 1

Related Questions