Unsupervised Machine Learning in R: K-Means

[This article was first published on R code – data technik, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

K-Means clustering is unsupervised machine learning because there is not a target variable. Clustering can be used to create a target variable, or simply group data by certain characteristics.

Here’s a great and simple way to use R to find clusters, visualize and then tie back to the data source to implement a marketing strategy.

#import dataset
ABC <-read.table("AbcBank.csv",header=TRUE, 

#choose variables to be clustered 
# make sure to exclude ID fields or Dates
ABC_num<- ABC[,2:5]
#scale the data! so they are all normalized 
ABC_scaled <-as.data.frame(scale(ABC_num))

#kmeans function
k3<- kmeans(ABC_scaled, centers=3, nstart=25)
#library with the visualization
fviz_cluster(k3, data=ABC_scaled,
             axes =c(1,2),
#check out the centers 
# remember these are normalized but 
#higher values are higher values for the original data
#add the cluster to the original dataset!

Check out our awesome clusters:

Repo here with dataset: https://github.com/emileemc/kmeans

To leave a comment for the author, please follow the link and comment on their blog: R code – data technik.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)