Kmeansrcode
Kmeansrcode
> View(iris)
> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width
Species
1 5.1 3.5 1.4 0.2
setosa
2 4.9 3.0 1.4 0.2
setosa
3 4.7 3.2 1.3 0.2
setosa
4 4.6 3.1 1.5 0.2
setosa
5 5.0 3.6 1.4 0.2
setosa
6 5.4 3.9 1.7 0.4
setosa
> x = iris[,-5]
> y = iris$Species
> kc <- kmeans(x,3)
> kc
K-means clustering with 3 clusters of sizes 38, 62, 50
Cluster means:
Sepal.Length Sepal.Width Petal.Length Petal.Width
1 6.850000 3.073684 5.742105 2.071053
2 5.901613 2.748387 4.393548 1.433871
3 5.006000 3.428000 1.462000 0.246000
Clustering vector:
[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 2 2 1 2 2
2 2
[58] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 1 1 1 1 2 1 1 1 1 1
1 2
[115] 2 1 1 1 1 2 1 2 1 2 1 1 2 2 1 1 1 1 1 2 1 1 1 1 2 1
1 1 2 1 1 1 2 1 1 2
Available components:
y 1 2 3
setosa 0 0 50
versicolor 2 48 0
virginica 36 14 0
> plot(x[c("Sepal.Length", "Sepal.Width")], col=kc$cluster)
> points(kc$centers[,c("Sepal.Length", "Sepal.Width")], col=1:3, pch=23,
cex=3)