R
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Data Structures
-
Section 4: Data Manipulation
-
Section 5: Visualization and Statistics
-
Section 6: Advanced R
-
Section 7: Practical Projects
-
Section 8: Interview Practice
-
Section 9: More Practice Exercises
-
Section 10: Shiny Apps in Depth
-
Section 11: More Data Wrangling
-
Section 12: Tidyverse Deep Dive
-
Section 13: Statistical Modeling Deep Dive
-
Section 14: Machine Learning in R
-
Section 15: R Visualization Deep Dive
-
Section 16: R Package Development Deep Dive
-
Section 17: R for Reproducible Research
-
Section 18: R and Databases
-
Section 19: R Performance Optimization
-
Section 20: Bioinformatics and Specialized R
-
Section 21: More Shiny Practice
-
Section 22: More Practice Exercises
-
Section 23: R Data Structures Deep Dive
-
Section 24: More Interview and Review
-
Section 25: R for Business Analytics
-
Section 26: R Text Mining and NLP
-
Section 27: R Spatial Data Analysis
-
Section 28: R Deep Learning
-
Section 29: Advanced Statistical Techniques
-
Section 30: R Object Systems Deep Dive
-
Section 31: R Environments and Metaprogramming
-
Section 32: R for Finance
-
Section 33: R for Clinical and Health Data
-
Section 34: More Shiny Advanced Practice
-
Section 35: R Data Cleaning Deep Dive
-
Section 36: R Reporting Automation
-
Section 37: More Practical Projects Round 2
-
Section 38: R Ecosystem and Career
-
Section 39: More Visualization Practice
-
Section 40: R for Experimentation
-
Section 41: R for Genomics and Bioinformatics Deep Dive
-
Section 42: R for Marketing Analytics
-
Section 43: R Data Import/Export Deep Dive
-
Section 44: R String Processing Deep Dive
-
Section 45: R for Actuarial and Insurance Analytics
-
Section 46: R Testing and Quality Assurance Deep Dive
-
Section 47: R Version Control and Collaboration
-
Section 48: R Advanced Functional Programming
-
Section 49: R for Supply Chain and Operations
-
Section 50: More Practice Exercises Round 3
-
Section 51: R Dashboards and BI Integration
-
Section 52: R Data Governance and Ethics
-
Section 53: More Modeling Practice
-
Section 54: R Final Capstone Projects
-
Section 55: R for Sports Analytics
-
Section 56: More Interview Practice Round 2
-
Section 57: R Networking and APIs
-
Section 58: R for Environmental Science
-
Section 59: R Notebook and Documentation Practices
-
Section 60: More Data Wrangling Mastery
-
Section 61: R for A/B Testing at Scale
-
Section 62: R Package Ecosystem Deep Dive
102: Customer Segmentation Analysis in R
Imagine you’ve just inherited a massive bin of mixed LEGO bricks from a sibling. If you want to build something specific, you can't just dig through the whole pile every time. You start sorting. You put all the tiny 1x1 studs in one pile, the long thin beams in another, and maybe all the red pieces in a third. You aren't following a strict rulebook; you're just grouping things that "look" like they belong together based on a few characteristics—color, size, or shape.
Customer segmentation is exactly that, just with data instead of plastic bricks. Instead of sorting by color, we're sorting by behavior. In R, we use clustering algorithms (most commonly K-means) to do the heavy lifting. We take a customer's "features"—like how much they spend or how often they visit—and let the computer find the "piles" for us.
Turning Raw Data into Personas
Before we can cluster, we need the right metrics. In the industry, we often use RFM analysis: Recency (how long since the last purchase), Frequency (how often they buy), and Monetary value (total spend). If we're analyzing a high-end coffee equipment store, a customer who bought a $2,000 espresso machine yesterday is very different from someone who buys a $15 bag of beans every two weeks.
One thing I've learned the hard way: K-means is obsessed with scale. If your "Total Spend" is in the thousands but your "Visit Frequency" is between 1 and 10, the algorithm will practically ignore the frequency because the spend numbers are so much larger. We have to scale the data first.
# Let's assume we have a dataframe called 'coffee_data'
# We select our RFM columns and scale them
rfm_scaled <- scale(coffee_data[, c("recency", "frequency", "monetary")])
Finding the Sweet Spot for Cluster Counts
The trickiest part of K-means is that you have to tell R how many clusters (K) you want. But how do you know if your customers naturally fall into three groups or twelve? You can't just guess; that's how you end up with meaningless segments.
I usually rely on the "Elbow Method." We run the clustering multiple times with different values of K and plot the total within-cluster sum of squares (WSS). We're looking for the point where the graph bends sharply—the "elbow." Past that point, adding more clusters doesn't give us much more insight; it just overcomplicates the model.
# Checking WSS for K = 1 through 10
wss <- sapply(1:10, function(k){
kmeans(rfm_scaled, centers = k, nstart = 20)$tot.withinss
})
plot(1:10, wss, type="b", pch = 19, frame = FALSE,
xlab="Number of Clusters K",
ylab="Total within-clusters sum of squares")
Mapping the Segments to Reality
Once we've picked our K—let's say 4—we run the final model and attach those group assignments back to our original data. This is where the magic happens. The numbers stop being just coordinates and start becoming "personas."
# Run K-means with 4 clusters
set.seed(123) # Keep it reproducible
final_clusters <- kmeans(rfm_scaled, centers = 4, nstart = 25)
# Add the cluster assignment back to the original data
coffee_data$segment <- as.factor(final_clusters$cluster)
# Let's see the average behavior for each group
aggregate(. ~ segment, data = coffee_data, FUN = mean)
Now you can look at the results and say, "Cluster 1 has high spend but low frequency—those are my 'Luxury Occasional' buyers. Cluster 3 has high frequency but low spend—those are my 'Daily Ritual' loyalists." I find that giving these groups names makes it much easier to explain your findings to people who don't care about K-means centroids.
📋 Practical Task
Building a High-Value Customer Identifier for a Boutique Bookstore
You have been given a dataset called bookstore_customers containing 500 rows. The dataset has three columns: avg_book_price (the average price of books they buy), books_per_year (how many books they purchase annually), and years_as_member (how long they've been a customer).
Your goal is to segment these customers into 3 distinct groups to help the marketing team create targeted email campaigns.
Your requirements:
- Scale the three numerical variables using the
scale()function. - Execute a K-means clustering algorithm to create exactly 3 clusters.
- Add a new column to the original
bookstore_customersdataframe calledcustomer_tierbased on the cluster results. - Use the
aggregate()function to calculate the mean ofavg_book_priceandbooks_per_yearfor each tier. - Identify which tier represents the "Whales" (the customers with the highest average spend and highest volume of books) and print that tier number to the console.
There are no comments for now.