R语言有自己封装的K-Means函数 ,可以直接调用
kmeans(x, centers, iter.max = 10, nstart = 1,
algorithm = c("Hartigan-Wong", "Lloyd", "Forgy",
"MacQueen")
可以使用?kmeans查看具体用法 在此不再赘述,万能的iris
data(iris)
newiris = iris[,-5]
(kc <- kmeans(newiris, 3))
table(iris$Species, kc$cluster)
plot(newiris[c("Sepal.Length", "Sepal.Width")], col = kc$cluster)
points(kc$centers[,c("Sepal.Length", "Sepal.Width")], col = 1:3, pch = 8, cex=2)
plot(newiris[c("Petal.Length", "Petal.Width")], col = kc$cluster)
points(kc$centers[,c("Petal.Length", "Petal.Width")], col = 1:3, pch = 8, cex=2)