# Load the packages in ----------------------------------------------------
if(!require(tidyverse)){install.packages("tidyverse"); library(tidyverse)}
if(!require(patchwork)){install.packages("patchwork"); library(patchwork)}
if(!require(ggplot2)){install.packages("ggplot2"); library(ggplot2)}
if(!require(ggwordcloud)){install.packages("ggwordcloud"); library(ggwordcloud)}
if(!require(ggpmisc)){install.packages("ggpmisc"); library(ggpmisc)}
if(!require(ggimage)){install.packages("ggimage"); library(ggimage)}
if(!require(ggtext)){install.packages("ggtext"); library(ggimage)}
if(!require(rlist)){install.packages("rlist"); library(rlist)}
if(!require(factoextra)){install.packages("factoextra"); library(factoextra)}
if(!require(NbClust)){install.packages("NbClust"); library(NbClust)}
# I stick all my styling into a CUsotm PAckage to tidy up my code and keep it consistent over the time
if(!require(CustomGGPlot2Theme)){devtools::install("CustomGGPlot2Theme"); library(CustomGGPlot2Theme)}
# get the wd - force of habit
wd <- getwd()
#pulling images off internet was taking a lot of time and casing a time out error
options(timeout = 1000)
font <- "noto_mono"
penguins <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/main/data/2025/2025-04-15/penguins.csv')
penguins_clean <- penguins %>%
select(sex, island, bill_len, bill_dep, flipper_len, body_mass) %>%
na.omit() %>%
mutate(
sex = as.numeric(factor(sex)),
island = as.numeric(factor(island))
)
# Find the optimal number of clusters using elbow method
# nb <- NbClust(penguins_clean, distance = "euclidean", min.nc = 2, max.nc = 10, method = "kmeans")
k <- 2
clust_kmeans <- eclust(penguins_clean, k=k, FUNcluster="kmeans", hc_metric="euclidean", graph=FALSE)
kmeans_silhouette <- fviz_silhouette(clust_kmeans, print.summary = FALSE)
kmeans_graph_2_clusters <- fviz_cluster(clust_kmeans, data = penguins_clean) +
Custom_Style()
#Now lets try with 3 clusters
k <- 3
# clust_kmeans <- eclust(penguins_clean, k=k, FUNcluster="kmeans", hc_metric="euclidean", graph=FALSE)
kmeans_silhouette <- fviz_silhouette(clust_kmeans, print.summary = FALSE)
kmeans_graph_3_clusters <- fviz_cluster(clust_kmeans, data = penguins_clean, labelsize = 0) +
Custom_Style() +
labs(title = "K-means Clustering of Penguins (PCA Projection) using R and ggplot2")