Suddenly, an error message, "Number of clusters 'k' must be in {1,2, .., n-1}; hence n >= 2", is displayed.

Dear community

Could you teach me what is the cause for this code?

Previously, I could execute the same code which csv was a few more rows...

Is it due to the small number of csv rows?

Although the likelihood of this is quite low...

x = read.csv("mydata.csv", header = TRUE, row.names = 1)

y = as.matrix(x)

for(i in 2:(nrow(y)-1)){
    pam(y, k = i, metric = "euclidean")
}
#metric="euclidean" may not need

fviz_nbclust(y, pam, method = "wss")

Error in FUNcluster(x, i, ...) : 
  Number of clusters 'k' must be in {1,2, .., n-1}; hence n >= 2

Test stepwise following this pattern

library(cluster)
library(factoextra)
#> Loading required package: ggplot2
#> Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
# the next statement does not return anything
for(i in 2:(nrow(mtcars)-1)) pam(mtcars,i)
# mtcars has dim 32 11
fviz_nbclust(mtcars, pam, method = "wss")

# try with dim 16 11
fviz_nbclust(mtcars[1:16,], pam, method = "wss")

# # try with dim 8 11
fviz_nbclust(mtcars[1:8,], pam, method = "wss")
#> Error in FUNcluster(x, i, ...): Number of clusters 'k' must be in {1,2, .., n-1}; hence n >= 2

Created on 2023-01-31 with reprex v2.0.2

Thank you for your prompt reply!

I already know it and could execute until these days ago.

I could chart using method wss, silhouette and gap_stat.

But only this time, it didn't go well...

it could work for k=7

fviz_nbclust(mtcars[1:8,], pam, method = "wss",k=7)

I'm sorry for the misleading text.

By "this time", I mean mydata.csv, not mtcars.

yes; we don't have your data; mtcars is an example ...

you have some code that before fviz_nblust, manually runs pam through possibilities; but you dont capture that; or look at it for anything....

You might consider changing it so that it shows you that highest possible k; you could then use that in fviz_nbclust

library(cluster)
y <- mtcars[1:8,]
for(i in 2:(nrow(y)-1)){
  pamx <- pam(y, k = i, metric = "euclidean")
  cat("k = ", i,"\n")
  print(unique(pamx$clustering))
}

note here mtcars is an example; that all forum users can use.
you could have provided your own example; but you didnt...
If you want to read advice on providing custom examples; I would encourage you to look here :

1 Like

Thank you very much for your long time and patience.

I will consider other ways of presenting the data and try this and that!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.