# Standard kmeans
kmeans(iris, centers = 3)
# formula interface can be used to select certain variables
kmeans(iris, ~ Petal.Width + Sepal.Width, centers = 3)
#... or create new variables. Consider non-linear example:
# Create data for two circles
x <- matrix(rnorm(300),nc=2)
y <- x/sqrt(rowSums(x^2))
d <- data.frame(rbind(y, y*5))
plot(d)
fit <- kmeans(d, centers = 2)
plot(d, col = predict(fit, d))
fit <- kmeans(d, ~ X1 + X2 + I(X1^2 + X2^2), centers = 2)
plot(d, col = predict(fit, d))
Run the code above in your browser using DataLab