MENU

Fun & Interesting

How to Apply PCA before K-means Clustering in R Programming (Example) | Principal Component Analysis

Statistics Globe 5,549 lượt xem 1 year ago
Video Not Working? Fix It Now

How to apply a K-means clustering algorithm after applying a PCA in the R programming language. The video also offers a preview of the upcoming Statistics Globe online course on "Principal Component Analysis (PCA): From Theory to Application in R". More details: https://statisticsglobe.com/online-course-pca-theory-application-r

R code of this video:

install.packages("factoextra") # Install & load factoextra
library("factoextra")

data(iris) # Load data
head(iris) # Print first rows of data

iris_num <- iris[ , 1:4] # Remove categorical variable
head(iris_num) # Print first rows of final data

my_pca <- prcomp(iris_num, # Perform PCA
scale = TRUE)
summary(my_pca) # Summary of explained variance

my_pca_data <- data.frame(my_pca$x[ , 1:2]) # Extract PC1 and PC2
head(my_pca_data) # Print first rows of PCA data

fviz_nbclust(my_pca_data, # Determine number of clusters
FUNcluster = kmeans,
method = "wss")

set.seed(123) # Set seed for reproducibility
my_kmeans <- kmeans(my_pca_data, # Perform k-means clustering
centers = 3)

fviz_pca_ind(my_pca, # Visualize clusters
habillage = my_kmeans$cluster,
label = "none",
addEllipses = TRUE)

Follow me on Social Media:
Facebook – Statistics Globe Page: https://www.facebook.com/statisticsglobecom/
Facebook – R Programming Group for Discussions & Questions: https://www.facebook.com/groups/statisticsglobe
Facebook – Python Programming Group for Discussions & Questions: https://www.facebook.com/groups/statisticsglobepython
LinkedIn – Statistics Globe Page: https://www.linkedin.com/company/statisticsglobe/
LinkedIn – R Programming Group for Discussions & Questions: https://www.linkedin.com/groups/12555223/
LinkedIn – Python Programming Group for Discussions & Questions: https://www.linkedin.com/groups/12673534/
Twitter: https://twitter.com/JoachimSchork
Instagram: https://www.instagram.com/statisticsglobecom/
TikTok: https://www.tiktok.com/@statisticsglobe

Comment