[R] kmeans

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Tue Feb 28 17:50:35 CET 2006



David Bitner wrote:
> Is there any way that I can assure that kmeans always returns the same
> result for the same data by locking down the random number generator
> or anything else?
> 
> David
> 

Try ?set.seed before your call to kmeans:

# from ?kmeans
# a 2-dimensional example
x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
            matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")

# set seed for random number generator
set.seed(42)
cl.1 <- kmeans(x, 5, nstart = 25)
set.seed(42)
cl.2 <- kmeans(x, 5, nstart = 25)

# check whether objects are identical
all.equal(cl.1, cl.2)

HTH,
--sundar




More information about the R-help mailing list