Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Clustering

suppressPackageStartupMessages({
    library(tidyverse)
    library(cowplot)
    library(broom)
    library(dbscan)
    theme_set(theme_cowplot())
})
options(repr.plot.width=15,repr.plot.height=9)

Clustering

k-means clustering

data("penguins", package = "modeldata")
head(penguins,3)

data <- na.omit(penguins)
Loading...
kmeans.obj <- 
    select(data, bill_length_mm, bill_depth_mm) |>
    kmeans(centers=3)
glance(kmeans.obj)
tidy(kmeans.obj)
Loading...
Loading...
augment(kmeans.obj, data) |>
ggplot(aes(x=bill_length_mm, y=bill_depth_mm, color=.cluster)) +
geom_point() +
geom_point(data=tidy(kmeans.obj), shape=4, size=3, stroke=2, aes(color='centroid'))  +
stat_ellipse()
plot without title

hierarchical clustering

select(data, bill_length_mm, bill_depth_mm) |>
as.matrix() |>
dist(method = 'canberra') |>
hclust(method='ward.D2') -> hc
plot(hc)
Plot with title "Cluster Dendrogram"
mutate(data, cluster=factor(cutree(hc, k=3))) |>
ggplot(aes(x=bill_length_mm, y=bill_depth_mm, color=cluster, group=cluster)) +
geom_point() +
stat_ellipse()
plot without title

density clustering

data(DS3, package='dbscan')
ggplot(DS3, aes(x=X, y=Y)) + 
geom_point()
plot without title
dbscan.obj <- hdbscan(DS3, minPts = 25)
augment(dbscan.obj, DS3) |>
# cluster 0 is noise
mutate(.cluster=if_else(.cluster==0, NA, .cluster)) |>
ggplot(aes(x=X, y=Y, color=.cluster)) +
geom_point()
plot without title