library(tidyverse) # Data manipulation
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.5
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ ggplot2 3.5.1 ✔ tibble 3.2.1
## ✔ lubridate 1.9.4 ✔ tidyr 1.3.1
## ✔ purrr 1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggplot2) # Data visualization
library(gridExtra) # Load the package
##
## Attaching package: 'gridExtra'
##
## The following object is masked from 'package:dplyr':
##
## combine
#### **Step 2: Load the Dataset**
rfm_data <- read.csv("retail_rfm.csv")
#### **Step 3: Assign RFM Scores**
rfm_data <- rfm_data %>%
rename(
Monetary = revenue, # Rename for consistency
Frequency = number_of_orders, # Rename for consistency
Recency = recency_days # Rename for consistency
) %>%
mutate(
R_Score = ntile(-Recency, 5), # Lower recency (recent purchases) is better
F_Score = ntile(Frequency, 5), # Higher frequency (higher transactions) better
M_Score = ntile(Monetary, 5) # Higher monetary value (increased spending) is better
)
#### **Step 4: Assign the Customer Segments**
rfm_data <- rfm_data %>%
mutate(
Segment = case_when(
R_Score == 5 & F_Score == 5 & M_Score == 5 ~ "Best Customers",
R_Score >= 4 & F_Score >= 4 & M_Score >= 4 ~ "Loyal Customers",
R_Score >= 3 & F_Score >= 3 & M_Score >= 3 ~ "Potential Loyalists",
R_Score == 1 & F_Score == 1 ~ "Lost Customers",
TRUE ~ "Other"
)
)
#### **Step 5: View the Segmented Data**
head(rfm_data)
## customer_id Monetary Frequency Recency purchase zip_code R_Score F_Score
## 1 1 737.75 19 93 0 22181 4 5
## 2 2 299.75 10 419 0 21117 2 4
## 3 3 74.00 1 724 0 20850 1 1
## 4 4 178.00 2 793 0 22032 1 2
## 5 5 552.40 15 68 1 8527 4 5
## 6 6 137.00 3 120 0 22124 4 2
## M_Score Segment
## 1 5 Loyal Customers
## 2 4 Other
## 3 2 Lost Customers
## 4 3 Other
## 5 5 Loyal Customers
## 6 3 Other
### **4. Add the Visualizations**
#### **Bar Chart: The Customer Segment Distribution**
ggplot(rfm_data, aes(x=Segment, fill=Segment)) +
geom_bar() +
theme_bw() +
geom_text(stat="count", aes(label=..count..), vjust=0) +
labs(title ="RFM Customer Segments", x="Segment", y="Count") +
theme(axis.text.x = element_text(angle = 45, hjust=1))
## Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(count)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

ggplot(rfm_data, aes(x=Recency, y=Frequency, color=Segment)) +
geom_point(size=3) +
theme_bw() +
labs(title="Recency vs Frequency by Segment",
x="Recency (Days Since Last Purchase)",
y="Frequency (Total Transactions)")

ggplot(rfm_data, aes(x=Segment, y=Monetary, fill=Segment)) +
geom_boxplot() +
theme_bw() +
labs(title="Monetary Value by Customer Segment", x="Segment",
y="Total Monetary Value") +
theme(axis.text.x = element_text(angle = 45, hjust=1))

# Calculate average customer spending
average_spending <- mean(rfm_data$Monetary)
# Print the result
print(paste("The average customer spending is:", round(average_spending, 2)))
## [1] "The average customer spending is: 358.83"
# Calculate average spending for each customer segment
segment_avg_spending <- rfm_data %>%
group_by(Segment) %>%
summarise(Average_Spending = mean(Monetary, na.rm = TRUE))
# Print average spending for each segment
for (i in 1:nrow(segment_avg_spending)) {
print(paste("Average spending for", segment_avg_spending$Segment[i], ":",
round(segment_avg_spending$Average_Spending[i], 2)))
}
## [1] "Average spending for Best Customers : 1341.91"
## [1] "Average spending for Lost Customers : 54.83"
## [1] "Average spending for Loyal Customers : 716.3"
## [1] "Average spending for Other : 154.79"
## [1] "Average spending for Potential Loyalists : 360.58"
### **5. Pie Charts: Purchasing Behavior by Segment**
# Filter the customers who purchased and did not purchase
purchased_data <- rfm_data %>% filter(purchase == 1)
not_purchased_data <- rfm_data %>% filter(purchase == 0)
# Count of the segments for each group
purchased_counts <- purchased_data %>% count(Segment)
not_purchased_counts <- not_purchased_data %>% count(Segment)
# Create the Pie Chart Function
plot_pie_chart <- function(data, title) {
ggplot(data, aes(x="", y=n, fill=Segment)) +
geom_bar(stat="identity", width=1) +
coord_polar(theta="y") +
theme_void() +
labs(title = title, fill = "Segment") +
geom_text(aes(label = paste0(round(n/sum(n)*100, 1), "%")),
position = position_stack(vjust=0.5))
}
# Generate the Pie Charts
p1 <- plot_pie_chart(purchased_counts, "Customers Who did Purchase (Segmented)")
p2 <- plot_pie_chart(not_purchased_counts, "Customers Who Didn't Purchase (Segmented)")
grid.arrange(p1, p2, ncol=2)
