Install all packages needed
#install.packages("mixtools")
#install.packages("cluster")
#install.packages("fpc")
The data was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973-74 models). We want to cluster the Car Models according to their mpg Miles/(US) gallon
library(mixtools)
## Loading required package: boot
## Loading required package: MASS
## Loading required package: segmented
## mixtools package, version 1.0.3, Released 2015-04-18
## This package is based upon work supported by the National Science Foundation under Grant No. SES-0518772.
mpg = mtcars[,1]
names(mpg)=row.names(mtcars)
hist(mpg,breaks=10)####We expect there are four clusters from the histogram
First, we use Kmeans clustering method to cluster car models, using the function kmeans() in R
library(cluster)
library(fpc)
kmeansresult=kmeans(mpg, centers=4)
show(kmeansresult)
## K-means clustering with 4 clusters of sizes 9, 10, 8, 5
##
## Cluster means:
## [,1]
## 1 22.47778
## 2 13.98000
## 3 18.30000
## 4 30.88000
##
## Clustering vector:
## Mazda RX4 Mazda RX4 Wag Datsun 710
## 1 1 1
## Hornet 4 Drive Hornet Sportabout Valiant
## 1 3 3
## Duster 360 Merc 240D Merc 230
## 2 1 1
## Merc 280 Merc 280C Merc 450SE
## 3 3 3
## Merc 450SL Merc 450SLC Cadillac Fleetwood
## 3 2 2
## Lincoln Continental Chrysler Imperial Fiat 128
## 2 2 4
## Honda Civic Toyota Corolla Toyota Corona
## 4 4 1
## Dodge Challenger AMC Javelin Camaro Z28
## 2 2 2
## Pontiac Firebird Fiat X1-9 Porsche 914-2
## 3 4 1
## Lotus Europa Ford Pantera L Ferrari Dino
## 4 2 3
## Maserati Bora Volvo 142E
## 2 1
##
## Within cluster sum of squares by cluster:
## [1] 23.95556 36.35600 8.64000 24.70800
## (between_SS / total_SS = 91.7 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss"
## [5] "tot.withinss" "betweenss" "size" "iter"
## [9] "ifault"
plot(mpg,col=kmeansresult$cluster)
For the same data-set, we use Hierarchical Clustering using the function hclust() in R
hclustresult=hclust(dist(mpg))
hclustresult
##
## Call:
## hclust(d = dist(mpg))
##
## Cluster method : complete
## Distance : euclidean
## Number of objects: 32
plot(hclustresult)