1
$\begingroup$

Hi there I am running a k-means code in R with the same data and with the same number of clusters, in this case 3, but each time that I run the code, the cluster label changes, for example.

In the first run I got this results

Col A Cluster.K-means

FirstOBS Cluster1,

SecondOBS Cluster1,

ThirdOBS Cluster2,

FourthOBS Cluster3

then I run the code again, specifying the same number of clusters=3, and the output column changes the cluster number, for example

FirstOBS Cluster2,

SecondOBS Cluster2,

ThirdOBS Cluster3,

FourthOBS Cluster1

In this case the second run (with the same data, same code and same number of clusters) changed the (1 by 2), the (2 by 3) and the (3 by 1)

How can I fix the result? because in the next step I have to compare the cluster number between two different data, for instance the cluster results from January against March results.

This is the code

cv1.km3 <- kmeans(cv1.f, 3) cv1.km3$size

So each time I run the cv1.km3$size I got different combinations

Thank you

$\endgroup$

1 Answer 1

1
$\begingroup$

Citing the reference documentation:

The algorithm of Hartigan and Wong (1979) is used by default. [...] The Hartigan–Wong algorithm generally does a better job than either of those, but trying several random starts (nstart> 1) is often recommended. In rare cases, when some of the points (rows of x) are extremely close, the algorithm may not converge in the “Quick-Transfer” stage, signalling a warning (and returning ifault = 4). Slight rounding of the data may be advisable in that case.

So at each iteration you get different results as expected. The way to avoid this, is to set the random seed to a fix number, so that the behaviour of the algorithm is deterministic. See set.seed for details.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.