library(learnr) knitr::opts_chunk$set(echo = TRUE, exercise = FALSE)
We firstly load the libraries.
library(RColorBrewer)
We load the data.
df <- iris[, 1:4]
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 = "")
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='')
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))
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])
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.