This project analyzes retail transaction data from
GroceryDataSet.csv, where each row represents an individual
transaction (basket) and columns list the items purchased.
The key objectives are:
Data Preprocessing & Exploration: Load
transactional data into a suitable format using the arules
package.
Association Rule Mining (Apriori Algorithm):
Mine association rules.
Evaluate rules using Support, Confidence, and Lift.
Extract and interpret the Top 10 rules ranked by Lift.
Extra Credit: Cluster Analysis:
Item-level hierarchical clustering based on Jaccard Dissimilarity.
Parameter optimization via Elbow Method and Silhouette Analysis.
Transaction-level segmentation via \(k\)-means clustering.
Dimensionality reduction ordination (PCA biplot) and behavioral profiling across customer groups.
We load arules for rule mining, arulesViz
for network visuals, tidyverse and tidytext
for wrangling/visualization, and
factoextra/cluster for unsupervised
segmentation.
required_packages <- c("arules", "arulesViz", "tidyverse", "tidytext", "cluster", "factoextra", "cowplot")
new_packages <- required_packages[!(required_packages %in% installed.packages()[, "Package"])]
if (length(new_packages) > 0) {
install.packages(new_packages, repos = "[https://cloud.r-project.org](https://cloud.r-project.org)")
}
library(arules)
library(arulesViz)
library(tidyverse)
library(tidytext)
library(cluster)
library(factoextra)
library(cowplot)Because grocery receipt files vary in column counts (ragged arrays),
reading them via read.transactions() from
arules directly parses comma-separated item lists into a
sparse transactions object.
trans <- read.transactions(
file = "GroceryDataSet.csv",
format = "basket",
sep = ",",
rm.duplicates = TRUE
)
summary(trans)## transactions as itemMatrix in sparse format with
## 9835 rows (elements/itemsets/transactions) and
## 169 columns (items) and a density of 0.02609146
##
## most frequent items:
## whole milk other vegetables rolls/buns soda
## 2513 1903 1809 1715
## yogurt (Other)
## 1372 34055
##
## element (itemset/transaction) length distribution:
## sizes
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
## 2159 1643 1299 1005 855 645 545 438 350 246 182 117 78 77 55 46
## 17 18 19 20 21 22 23 24 26 27 28 29 32
## 29 14 14 9 11 4 6 1 1 1 1 3 1
##
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.000 2.000 3.000 4.409 6.000 32.000
##
## includes extended item information - examples:
## labels
## 1 abrasive cleaner
## 2 artif. sweetener
## 3 baby cosmetics
Before mining rules, we examine transaction size distribution and the most frequently purchased grocery items.
itemFrequencyPlot(
trans,
topN = 20,
type = "relative",
main = "Top 20 Most Frequent Items",
col = "steelblue",
ylab = "Relative Frequency (Support)"
)Support (\(s\)): The proportion of transactions that contain both \(\{X, Y\}\): \[\text{Support}(X \Rightarrow Y) = P(X \cap Y)\]
Confidence (\(c\)): How frequently \(Y\) appears in baskets that contain \(X\): \[\text{Confidence}(X \Rightarrow Y) = \frac{P(X \cap Y)}{P(X)}\]
Lift: Ratio of observed joint probability to expected joint probability under independence: \[\text{Lift}(X \Rightarrow Y) = \frac{P(X \cap Y)}{P(X) \cdot P(Y)}\] A lift \(> 1\) indicates a positive association between items.
We set a baseline of supp = 0.001 and
conf = 0.5 with a minimum basket length of 2 to filter out
single-item trivialities.
## Apriori
##
## Parameter specification:
## confidence minval smax arem aval originalSupport maxtime support minlen
## 0.5 0.1 1 none FALSE TRUE 5 0.001 2
## maxlen target ext
## 10 rules TRUE
##
## Algorithmic control:
## filter tree heap memopt load sort verbose
## 0.1 TRUE TRUE FALSE TRUE 2 TRUE
##
## Absolute minimum support count: 9
##
## set item appearances ...[0 item(s)] done [0.00s].
## set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s].
## sorting and recoding items ... [157 item(s)] done [0.00s].
## creating transaction tree ... done [0.00s].
## checking subsets of size 1 2 3 4 5 6 done [0.01s].
## writing ... [5668 rule(s)] done [0.00s].
## creating S4 object ... done [0.00s].
## set of 5668 rules
##
## rule length distribution (lhs + rhs):sizes
## 2 3 4 5 6
## 11 1461 3211 939 46
##
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 2.00 3.00 4.00 3.92 4.00 6.00
##
## summary of quality measures:
## support confidence coverage lift
## Min. :0.001017 Min. :0.5000 Min. :0.001017 Min. : 1.957
## 1st Qu.:0.001118 1st Qu.:0.5455 1st Qu.:0.001729 1st Qu.: 2.464
## Median :0.001322 Median :0.6000 Median :0.002135 Median : 2.899
## Mean :0.001668 Mean :0.6250 Mean :0.002788 Mean : 3.262
## 3rd Qu.:0.001729 3rd Qu.:0.6842 3rd Qu.:0.002949 3rd Qu.: 3.691
## Max. :0.022267 Max. :1.0000 Max. :0.043416 Max. :18.996
## count
## Min. : 10.0
## 1st Qu.: 11.0
## Median : 13.0
## Mean : 16.4
## 3rd Qu.: 17.0
## Max. :219.0
##
## mining info:
## data ntransactions support confidence
## trans 9835 0.001 0.5
## call
## apriori(data = trans, parameter = list(supp = 0.001, conf = 0.5, minlen = 2, maxlen = 10))
We identify and remove redundant rule subsets where a broader antecedent provides equal or superior confidence.
subset_matrix <- is.subset(rules, rules)
diag(subset_matrix) <- FALSE
redundant <- apply(subset_matrix, 2, any)
rules_clean <- rules[!redundant]
cat("Total mined rules:", length(rules), "\n")## Total mined rules: 5668
## Cleaned (non-redundant) rules: 1755
Rules can occasionally contain subsets that provide no additional lift or information. We remove redundant rules to ensure concise insights.
## lhs rhs support confidence coverage lift count
## [1] {Instant food products,
## soda} => {hamburger meat} 0.001220132 0.6315789 0.001931876 18.995654 12
## [2] {baking powder,
## flour} => {sugar} 0.001016777 0.5555556 0.001830198 16.408075 10
## [3] {ham,
## processed cheese} => {white bread} 0.001931876 0.6333333 0.003050330 15.045491 19
## [4] {domestic eggs,
## processed cheese} => {white bread} 0.001118454 0.5238095 0.002135231 12.443639 11
## [5] {liquor,
## red/blush wine} => {bottled beer} 0.001931876 0.9047619 0.002135231 11.235269 19
## [6] {frozen vegetables,
## specialty chocolate} => {fruit/vegetable juice} 0.001016777 0.6250000 0.001626843 8.645394 10
## [7] {frozen vegetables,
## root vegetables,
## yogurt} => {whipped/sour cream} 0.001321810 0.5200000 0.002541942 7.254184 13
## [8] {butter,
## hard cheese} => {whipped/sour cream} 0.002033554 0.5128205 0.003965430 7.154028 20
## [9] {liquor,
## soda} => {bottled beer} 0.001220132 0.5714286 0.002135231 7.095960 12
## [10] {chicken,
## citrus fruit,
## sausage} => {root vegetables} 0.001016777 0.7692308 0.001321810 7.057262 10
top10_df <- as(top10_lift, "data.frame")
knitr::kable(top10_df, caption = "Top 10 Association Rules Ranked by Lift")| rules | support | confidence | coverage | lift | count | |
|---|---|---|---|---|---|---|
| 53 | {Instant food products,soda} => {hamburger meat} | 0.0012201 | 0.6315789 | 0.0019319 | 18.995654 | 12 |
| 444 | {baking powder,flour} => {sugar} | 0.0010168 | 0.5555556 | 0.0018302 | 16.408075 | 10 |
| 327 | {ham,processed cheese} => {white bread} | 0.0019319 | 0.6333333 | 0.0030503 | 15.045491 | 19 |
| 330 | {domestic eggs,processed cheese} => {white bread} | 0.0011185 | 0.5238095 | 0.0021352 | 12.443639 | 11 |
| 18 | {liquor,red/blush wine} => {bottled beer} | 0.0019319 | 0.9047619 | 0.0021352 | 11.235269 | 19 |
| 634 | {frozen vegetables,specialty chocolate} => {fruit/vegetable juice} | 0.0010168 | 0.6250000 | 0.0016268 | 8.645394 | 10 |
| 3168 | {frozen vegetables,root vegetables,yogurt} => {whipped/sour cream} | 0.0013218 | 0.5200000 | 0.0025419 | 7.254184 | 13 |
| 708 | {butter,hard cheese} => {whipped/sour cream} | 0.0020336 | 0.5128205 | 0.0039654 | 7.154028 | 20 |
| 19 | {liquor,soda} => {bottled beer} | 0.0012201 | 0.5714286 | 0.0021352 | 7.095960 | 12 |
| 2853 | {chicken,citrus fruit,sausage} => {root vegetables} | 0.0010168 | 0.7692308 | 0.0013218 | 7.057262 | 10 |
Customer segmentation and product affinity structures can be captured via two complementary unsupervised perspectives:
Item-Level Co-occurrence Clustering: Grouping SKUs by binary co-purchase similarity across all transactions.
Transaction-Level Customer Segmentation: Grouping shopping carts by shared product combinations to delineate shopping missions.
Below, we cluster frequently purchased items using hierarchical
clustering on Jaccard distances, followed by a
transaction-level \(k\)-means
clustering on high-variance items.
Items bought in fewer than 1% of transactions are excluded to prevent excessive sparsity from distorting distance metrics. The Jaccard distance between two items \(i\) and \(j\) measures:
\[d_J(i, j) = 1 - \frac{\vert{}T_i \cap T_j\vert{}}{\vert{}T_i \cup T_j\vert{}}\]
where \(T_i\) and \(T_j\) represent transactions containing item \(i\) and item \(j\), respectively.
frequent_items <- trans[, itemFrequency(trans) > 0.01]
item_matrix <- t(as(frequent_items, "matrix"))
item_dist <- dist(item_matrix, method = "binary")
hc_items <- hclust(item_dist, method = "ward.D2")
plot(
hc_items,
main = "Dendrogram of Frequently Purchased Items (Ward's D2)",
xlab = "Grocery Products",
sub = "Binary Jaccard Dissimilarity",
cex = 0.75,
hang = -1
)
rect.hclust(hc_items, k = 5, border = c("#e63946", "#1d3557", "#2a9d8f", "#e76f51", "#8338ec"))We project transactions onto binary vectors across frequently purchased items (\(x_{ij} \in \{0, 1\}\)). To optimize computational throughput while maintaining statistical power, a reproducible sample of 3,000 transactions is drawn.
trans_matrix <- as(frequent_items, "matrix") * 1
set.seed(42)
sample_size <- min(3000, nrow(trans_matrix))
sample_idx <- sample(nrow(trans_matrix), sample_size)
sampled_trans <- trans_matrix[sample_idx, ]
cat("Incidence Matrix Dimensions:", nrow(sampled_trans), "baskets x", ncol(sampled_trans), "items\n")## Incidence Matrix Dimensions: 3000 baskets x 88 items
We evaluate candidate cluster counts \(k \in [2, 8]\) using both the Elbow Method (minimizing Total Within-Cluster Sum of Squares, WSS) and Average Silhouette Width (maximizing partition separation).
p_elbow <- fviz_nbclust(sampled_trans, kmeans, method = "wss", k.max = 8, nstart = 10) +
labs(title = "Optimal k: Elbow Method", subtitle = "WSS reduction across clusters") +
theme_minimal(base_family = "Inter")
p_sil <- fviz_nbclust(sampled_trans, kmeans, method = "silhouette", k.max = 8, nstart = 10) +
labs(title = "Optimal k: Silhouette Analysis", subtitle = "Average silhouette width across clusters") +
theme_minimal(base_family = "Inter")
plot_grid(p_elbow, p_sil, ncol = 2)In accordance with silhouette results and managerial
interpretability, we set \(k = 3\). We
fit the final \(k\)-means model using
\(25\) random initializations
(nstart = 25) to guarantee convergence to a global
minimum.
set.seed(42)
k_clusters <- kmeans(sampled_trans, centers = 3, nstart = 25)
cluster_counts <- table(Cluster = paste("Cluster", k_clusters$cluster))
knitr::kable(as.data.frame(cluster_counts), caption = "Transaction Distribution Across Clusters")| Cluster | Freq |
|---|---|
| Cluster 1 | 561 |
| Cluster 2 | 594 |
| Cluster 3 | 1845 |
We perform Principal Component Analysis (PCA) on the binary transaction incidence space to project customer baskets onto the two principal axes explaining the highest variance.
fviz_cluster(
k_clusters,
data = sampled_trans,
geom = "point",
ellipse.type = "convex",
palette = c("#2a9d8f", "#e76f51", "#3a86ff"),
ggtheme = theme_minimal(base_family = "Inter"),
main = "2D PCA Projection of Transaction Clusters"
) +
theme(legend.position = "bottom")The cluster center vectors \(\mathbf{c}_k = [c_{k1}, c_{k2}, \dots, c_{kp}]\) indicate the empirical probability that a transaction assigned to Cluster \(k\) contains item \(j\). We extract and plot the top 7 items per cluster.
centers_df <- as.data.frame(k_clusters$centers) %>%
rownames_to_column(var = "Cluster") %>%
pivot_longer(cols = -Cluster, names_to = "Item", values_to = "Probability") %>%
group_by(Cluster) %>%
slice_max(order_by = Probability, n = 7, with_ties = FALSE) %>%
ungroup()
ggplot(centers_df, aes(x = tidytext::reorder_within(Item, Probability, Cluster), y = Probability, fill = Cluster)) +
geom_col(show.legend = FALSE, width = 0.7) +
coord_flip() +
tidytext::scale_x_reordered() +
scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
facet_wrap(~ Cluster, scales = "free_y", ncol = 1) +
scale_fill_manual(values = c("1" = "#2a9d8f", "2" = "#e76f51", "3" = "#3a86ff")) +
labs(
title = "Top Characteristic Items by Cluster",
subtitle = "Item purchase probability conditional on cluster membership",
x = NULL,
y = "Conditional Purchase Probability"
) +
theme_minimal() +
theme(
strip.text = element_text(face = "bold", size = 12),
panel.grid.minor = element_blank()
)We verify whether cluster membership corresponds to basket size differences (quick single-item runs versus comprehensive grocery restocking).
basket_sizes <- data.frame(
Cluster = factor(paste("Cluster", k_clusters$cluster)),
BasketSize = rowSums(sampled_trans)
)
ggplot(basket_sizes, aes(x = Cluster, y = BasketSize, fill = Cluster)) +
geom_boxplot(alpha = 0.8, outlier.colour = "grey50", outlier.shape = 1) +
scale_fill_manual(values = c("#2a9d8f", "#e76f51", "#3a86ff")) +
labs(
title = "Transaction Basket Size Distribution by Cluster",
x = "Assigned Cluster",
y = "Number of Items per Basket"
) +
theme_minimal(base_family = "Inter") +
theme(legend.position = "none")Market Basket Rules:
High-lift associations (up to 19.00x expected baseline) reveal tight purchasing complements:
Produce pairs (e.g., citrus fruit, root vegetables, other vegetables) consistently exceed expected baseline purchase rates by factors of 3 to 4.
Dairy and bakery staples (whole milk,
yogurt, rolls/buns) frequently serve as
high-confidence consequents across multi-item basket
configurations.
Cluster Segmentation Archetypes:
Cluster 1 (Mean basket size: 5.4 items): Anchored by whole milk (100.0%), alongside rolls/buns (21.7%) and yogurt (19.8%).
Cluster 2 (Mean basket size: 6.9 items): Led by other vegetables (99.8%), followed by whole milk (39.9%) and root vegetables (26.3%).
Cluster 3 (Mean basket size: 2.8 items): Driven by rolls/buns (17.5%), paired with soda (17.3%) and canned beer (11.4%).