Skip to Content
Course content

102: Customer Segmentation Analysis in R

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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_customers dataframe called customer_tier based on the cluster results.
  • Use the aggregate() function to calculate the mean of avg_book_price and books_per_year for 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.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.