-
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
218: Capstone: Building a Customer Segmentation and Targeting System
Imagine you're organizing a massive wedding. You have a guest list of 500 people. You can't possibly write a unique, heartfelt note to every single person, but you also can't send the exact same generic "thanks for coming" card to your grandmother, your old college roommate, and your boss. Instead, you group them. You've got the "Inner Circle," the "Extended Family," and the "Professional Contacts." Once they're grouped, you can tailor your message—and your budget—to each group specifically.
Building a customer segmentation system in R works exactly like that. We aren't just looking at a list of names; we're looking for behavioral patterns. Here is how that analogy maps to the code we're about to write:
- The Guest List is your raw transaction dataset.
- The Relationship Criteria (how often you talk, how close you are) are your RFM metrics: Recency, Frequency, and Monetary value.
- The Grouping Process is the K-means clustering algorithm, which mathematically decides who belongs in which "bucket."
- The Tailored Message is your targeting strategy—deciding which group gets a discount code and which group gets a loyalty reward.
Turning Raw Transactions into Behavioral Signals
We can't just feed a list of every single purchase into a clustering algorithm; it's too noisy. We need to collapse those transactions into a "customer profile." In the industry, we almost always start with RFM. I've found that while there are fancier models, RFM is the "bread and butter" because it's easy to explain to stakeholders.
library(tidyverse)
library(lubridate)
# Assuming 'df' is our raw transaction data with CustomerID, Date, and Amount
rfm_data <- df %>%
group_by(CustomerID) %>%
summarise(
Recency = as.numeric(as.Date("2023-12-31") - max(Date)),
Frequency = n(),
Monetary = sum(Amount)
) %>%
drop_na()
# Clustering is sensitive to scale. If Monetary is in the thousands
# and Frequency is 1-10, the algorithm will ignore Frequency.
rfm_scaled <- scale(rfm_data[, 2:4])
Hunting for the Sweet Spot with the Elbow Method
The hardest part of K-means is deciding how many clusters (K) to actually use. If you pick too many, you're just overcomplicating things. Too few, and you're grouping "VIPs" with "one-time buyers." I usually rely on the "Elbow Method." We run the model for a range of K values and look for the point where the improvement in "within-cluster sum of squares" starts to flatten out.
library(factoextra)
# We'll check 1 through 10 clusters
fviz_nbclust(rfm_scaled, kmeans, method = "wss") +
labs(title = "Determining Optimal Clusters", x = "Number of Clusters", y = "Total Within-Cluster Sum of Squares")
When you look at that plot, you're looking for the "bend" in the arm. If the bend happens at K=4, that's your magic number. It means adding a fifth cluster doesn't actually give you much more insight.
Assigning Personas to the Clusters
Once we run the K-means, R gives us cluster numbers (1, 2, 3...), but "Cluster 1" means nothing to a marketing manager. This is where you step in as the analyst to assign a persona based on the cluster means.
# Running the model with 4 clusters
set.seed(123) # Keep it reproducible
km_res <- kmeans(rfm_scaled, centers = 4, nstart = 25)
# Add the cluster assignment back to our original data
rfm_final <- rfm_data %>%
mutate(Cluster = as.factor(km_res$cluster))
# Now, let's see who these people actually are
cluster_profiles <- rfm_final %>%
group_by(Cluster) %>%
summarise(
Avg_Recency = mean(Recency),
Avg_Freq = mean(Frequency),
Avg_Monetary = mean(Monetary)
)
At this point, I'd look at the cluster_profiles table. If Cluster 2 has low recency (bought recently), high frequency, and high monetary value, I'm labeling them "Champions." If Cluster 4 has high recency (hasn't been seen in months) and low frequency, they're "At-Risk."
Seeing the Segments in Action
Numbers are great, but a visualization is what sells the project. I prefer a 3D scatter plot or a series of 2D plots to ensure the clusters actually look separated. If they're just one giant blob, you might need to revisit your scaling or try a different number of clusters.
fviz_cluster(km_res, data = rfm_scaled,
geom = "point",
ellipse.type = "convex",
ggtheme = theme_minimal(),
main = "Customer Segment Visualization")
📋 Practical Task
Project: High-Value Customer Identification Pipeline for a Subscription Service
You have been handed a dataset of 1,000 subscribers for a streaming service. The dataset subscription_data.csv contains UserID, LastLoginDate, TotalMoviesWatched, and TotalSpend.
Your task is to build a complete segmentation pipeline. You must:
- Feature Engineer: Calculate the
Recency(days since last login relative to 2024-01-01),Frequency(TotalMoviesWatched), andMonetary(TotalSpend) for each user. - Pre-process: Scale the data to ensure
TotalSpenddoesn't dominate the clustering. - Optimize: Use the Elbow Method to justify your choice of K.
- Segment: Run the K-means algorithm and create a new column in your final dataframe called
UserSegment. - Analyze: Print a summary table showing the average values for each segment and assign a descriptive name to each segment (e.g., "Power Users", "Churn Risks", "Casuals") based on their behavior.
There are no comments for now.