library(learnr)
knitr::opts_chunk$set(echo = TRUE, exercise = FALSE)

Hierarchical Agglomerative Clustering

We firstly load the libraries.

library(RColorBrewer)

Loading the data

We load the data.

df <- iris[, 1:4]

Computing distances

We also compute the pairwise distances and plot the results.

iris_e <- dist(x = df, method = "euclidean")
image(1:150, 1:150, as.matrix(iris_e), main='Euclidean pairwise distances', asp=1, xlab = "", ylab = "")

Dendogram

We build dendograms considering different linkages.

iris_es <- hclust(d = iris_e, method='single')
iris_ea <- hclust(d = iris_e, method='average')
iris_ec <- hclust(d = iris_e, method='complete')

We plot the results we have obtained.

par(mfrow = c(1, 3))
plot(iris_es, main='Euclidean Single', hang=-0.1, xlab='', labels=FALSE, cex=0.6, sub='')
plot(iris_ec, main='Euclidean Complete', hang=-0.1, xlab='', labels=FALSE, cex=0.6, sub='')
plot(iris_ea, main='Euclidean Average', hang=-0.1, xlab='', labels=FALSE, cex=0.6, sub='')

Cophenetic Matrices

Moreover, we compute the cophenetic matrices.

coph_es <- cophenetic(iris_es)
coph_ec <- cophenetic(iris_ec)
coph_ea <- cophenetic(iris_ea)

and show the cophenetic indices.

(es <-cor(iris_e, coph_es))
(ec <-cor(iris_e, coph_ec))
(ea <-cor(iris_e, coph_ea))

Extracting clusters

Try to extract different clusters!

k <- 2
(cluster_ea <- cutree(tree = iris_ea, k = k))
pairs(df, col = brewer.pal(n = ifelse(k >= 3, k, 3), name = "Accent")[cluster_ea])


mascaretti/moxier documentation built on March 17, 2020, 3:57 p.m.