Introduction to Modern Mathematical Modeling with R:

A User’s Manual to Train Mathematical Consultants

 

A Cambridge University Press book by

SSP Shen

 

 

R Code written by Dr. Samuel Shen, Distinguished Professor
San Diego State University, California, USA
https://shen.sdsu.edu
Email:

 

Compiled and Edited by Joaquin Stawsky
San Diego State University, August 2022

 

 

 

Chapter 12: Concepts of Machine Learning

K-means Clustering

# K-Means Cluster Analysis for a 2D Random Point Set 
mydata <- matrix(runif(40),ncol=2)
fit <- kmeans(mydata, 5) # 5 cluster solution

# get cluster means 
aggregate(mydata,by=list(fit$cluster),FUN=mean)
##   Group.1        V1        V2
## 1       1 0.1137287 0.7244177
## 2       2 0.4356630 0.9366832
## 3       3 0.8953217 0.7985115
## 4       4 0.6653272 0.3016324
## 5       5 0.4361514 0.5551264
# append cluster assignment
mycluster <- data.frame(mydata, fit$cluster) 
library(animation)
kmeans.ani(mycluster, centers=5, pch=1:5, col=1:5)