I fit three different kemans models to the iris data set. Then, I would like to compare their
rand index (RI) using the for loop. If the RI of a model is larger than the second one, then stop the loop and return the largest values of RI.
For example, if the RI of the first model is larger than the RI of the second model, then
break the for loop and provide the RI of the first model. In my example, the RI of the second model is larger than the third model. Hence, the for loop should break and provide me with the value of the second model fit2$cluster. When I run the model it returns me the number 1, which is the first model and it is not correct. If there is a way to return the name of the model would be even better. Any help, please?
Here is my try:
library(aricode)## contain the RI function
fit1 <- kmeans(iris[,-5], centers = 2)
fit2 <- kmeans(iris[,-5], centers = 3)
fit3 <- kmeans(iris[,-5], centers = 4)
fit <- list(fit1$cluster, fit2$cluster, fit3$cluster)
Here is my for loop
for(i in seq_along(fit)){
if (RI(fit[[i]], iris[,5]) > RI(fit[[i+1]], iris[,5])) break
# x <- RI(fit[[i]], iris[,5])
print(i)
}