# Install Packages

library(arules)
## Loading required package: Matrix
## 
## Attaching package: 'arules'
## The following objects are masked from 'package:base':
## 
##     abbreviate, write
library(arulesViz)
# Import Dataset

data <- read.csv("C:/Users/Owner/Desktop/W4 - retail_transactions (2).csv", header = TRUE, row.names = 1)

# Display forst six rows
head(data)
##       Milk Bread Butter Eggs Cheese Juice Yogurt Cereal Coffee Tea Chips Fruit
## T0001    0     0      0    0      0     1      1      0      0   0     1     0
## T0002    0     0      0    0      0     0      0      0      1   1     1     0
## T0003    0     0      0    0      0     0      0      1      0   0     1     0
## T0004    0     0      1    0      0     0      0      1      1   0     1     0
## T0005    0     0      0    0      0     0      0      0      0   0     1     0
## T0006    1     0      0    0      0     0      0      1      1   0     0     0
##       Vegetables Meat Fish Rice Pasta Snacks Frozen.Foods Cleaning.Supplies
## T0001          0    0    0    0     1      0            0                 0
## T0002          0    0    0    1     0      1            0                 1
## T0003          0    0    0    0     0      0            0                 0
## T0004          0    1    0    0     1      0            0                 0
## T0005          1    1    1    0     0      1            0                 1
## T0006          0    0    0    0     0      1            1                 1
# Convert 0 and 1 into True and False 
data[] <- lapply(data, function(x) as.logical(x))

# Convert dataset into transactions format
transactions <- as(data, "transactions")
# Part A: Step 1 
# Display transaction summary
summary(transactions)
## transactions as itemMatrix in sparse format with
##  500 rows (elements/itemsets/transactions) and
##  20 columns (items) and a density of 0.2027 
## 
## most frequent items:
##       Coffee Frozen.Foods         Milk       Cereal       Butter      (Other) 
##          124          115          114          108          106         1460 
## 
## element (itemset/transaction) length distribution:
## sizes
##   2   3   4   5   6 
## 101  91 101  94 113 
## 
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   2.000   3.000   4.000   4.054   5.000   6.000 
## 
## includes extended item information - examples:
##   labels variables levels
## 1   Milk      Milk   TRUE
## 2  Bread     Bread   TRUE
## 3 Butter    Butter   TRUE
## 
## includes extended transaction information - examples:
##   transactionID
## 1         T0001
## 2         T0002
## 3         T0003
# Part A: Step 2 

## Count of total transactions
total_transactions <- length(transactions)

## Count unique products
total_items <- length(itemLabels(transactions))

## Display results
cat("Total Transactions:", total_transactions, "\n")
## Total Transactions: 500
cat("Total Unique Items:", total_items, "\n")
## Total Unique Items: 20
## Frequently Purchased Items

## Calculate individual item frequencies
item_frequency <- itemFrequency(
  transactions,
  type = "absolute"
)

## Sort products from most frequent to least frequent
sorted_items <- sort(
  item_frequency,
  decreasing = TRUE
)

## Display the top 5 products
head(sorted_items, 5)
##       Coffee Frozen.Foods         Milk       Cereal       Butter 
##          124          115          114          108          106
#### Analyzing the results: The dataset contains 500 transactions with a total of 20 unique products. Coffee is the most frequently purchased product, appearing in 124 transactions. Frozen foods and Milk come in next with frozen foods having 115 transactions and milk 114. Lastly, are cereal and butter with 108 transactions for cereal and 106 for butter. This code identify most frequently purchased item which is important for marketing, inventory, and product placement for retailers. 
# Part A: Step 3 (Find Top 5 Pairs)

## Generate frequent itemsets containing pairs
item_pairs <- eclat(
  transactions,
  parameter = list(
    support = 0.001,
    maxlen = 2
  )
)
## Eclat
## 
## parameter specification:
##  tidLists support minlen maxlen            target  ext
##     FALSE   0.001      1      2 frequent itemsets TRUE
## 
## algorithmic control:
##  sparse sort verbose
##       7   -2    TRUE
## 
## Absolute minimum support count: 0 
## 
## create itemset ... 
## set transactions ...[20 item(s), 500 transaction(s)] done [0.00s].
## sorting and recoding items ... [20 item(s)] done [0.00s].
## creating bit matrix ... [20 row(s), 500 column(s)] done [0.00s].
## writing  ... [210 set(s)] done [0.00s].
## Creating S4 object  ... done [0.00s].
## Keep only pairs of products
item_pairs <- item_pairs[size(item_pairs) == 2]

## Sort pairs by support
item_pairs <- sort(
  item_pairs,
  by = "support",
  decreasing = TRUE
)

## Display the top 5 pairs
inspect(head(item_pairs, 5))
##     items                  support count
## [1] {Coffee, Frozen.Foods} 0.066   33   
## [2] {Chips, Fish}          0.062   31   
## [3] {Coffee, Pasta}        0.058   29   
## [4] {Milk, Coffee}         0.058   29   
## [5] {Cereal, Coffee}       0.056   28
### Analyzing the results: Coffee and Frozen Foods are most commonly bought together with 33 total transactions, suggesting that shoppers sometimes purchase these two items in the same trip. Retailers could use this information to organize their products in a manner that is conducive to these findings to provide ease to the shoppers and to increase overall sales. Additionally, they could offer promotions or discounts to increase combined purchases.
# Part B: Part 1 (Apiori Algorithim / Support = 30% / Confidence = 60%)

## Generate association rules using Apriori
rules <- apriori(
  transactions,
  parameter = list(
    supp = 0.30,
    conf = 0.60,
    minlen = 2
  )
)
## Apriori
## 
## Parameter specification:
##  confidence minval smax arem  aval originalSupport maxtime support minlen
##         0.6    0.1    1 none FALSE            TRUE       5     0.3      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: 150 
## 
## set item appearances ...[0 item(s)] done [0.00s].
## set transactions ...[20 item(s), 500 transaction(s)] done [0.00s].
## sorting and recoding items ... [0 item(s)] done [0.00s].
## creating transaction tree ... done [0.00s].
## checking subsets of size 1 done [0.00s].
## writing ... [0 rule(s)] done [0.00s].
## creating S4 object  ... done [0.00s].
## Display the generated rules
inspect(rules)
# Part B: Step 2 Sort association rules by lift 

## Sort rules by lift
rules_sorted <- sort(
  rules,
  by = "lift",
  decreasing = TRUE
)

## Display the top rules
inspect(head(rules_sorted, 10))

## Create graph visualization
if (length(rules_sorted) > 0) {

  plot(
    rules_sorted,
    method = "graph",
    engine = "htmlwidget"
  )

} else {

  print("No association rules available at the required thresholds.")

}
## [1] "No association rules available at the required thresholds."
## Testing with lower threshold for better results

## Run exploratory Apriori analysis
exploratory_rules <- apriori(
  transactions,
  parameter = list(
    supp = 0.05,
    conf = 0.25,
    minlen = 2
  )
)
## Apriori
## 
## Parameter specification:
##  confidence minval smax arem  aval originalSupport maxtime support minlen
##        0.25    0.1    1 none FALSE            TRUE       5    0.05      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: 25 
## 
## set item appearances ...[0 item(s)] done [0.00s].
## set transactions ...[20 item(s), 500 transaction(s)] done [0.00s].
## sorting and recoding items ... [20 item(s)] done [0.00s].
## creating transaction tree ... done [0.00s].
## checking subsets of size 1 2 3 done [0.00s].
## writing ... [21 rule(s)] done [0.00s].
## creating S4 object  ... done [0.00s].
## Sort exploratory rules by lift
exploratory_sorted <- sort(
  exploratory_rules,
  by = "lift",
  decreasing = TRUE
)

## Display the top 10 rules
inspect(head(exploratory_sorted, 10))
##      lhs                    rhs                 support confidence coverage
## [1]  {Chips}             => {Fish}              0.062   0.2952381  0.210   
## [2]  {Fish}              => {Chips}             0.062   0.3039216  0.204   
## [3]  {Bread}             => {Cleaning.Supplies} 0.054   0.2872340  0.188   
## [4]  {Cleaning.Supplies} => {Bread}             0.054   0.2647059  0.204   
## [5]  {Bread}             => {Chips}             0.054   0.2872340  0.188   
## [6]  {Chips}             => {Bread}             0.054   0.2571429  0.210   
## [7]  {Tea}               => {Cleaning.Supplies} 0.050   0.2525253  0.198   
## [8]  {Pasta}             => {Fruit}             0.052   0.2500000  0.208   
## [9]  {Fruit}             => {Pasta}             0.052   0.2524272  0.206   
## [10] {Butter}            => {Eggs}              0.054   0.2547170  0.212   
##      lift     count
## [1]  1.447246 31   
## [2]  1.447246 31   
## [3]  1.408010 27   
## [4]  1.408010 27   
## [5]  1.367781 27   
## [6]  1.367781 27   
## [7]  1.237869 25   
## [8]  1.213592 26   
## [9]  1.213592 26   
## [10] 1.201495 27
# Visualize exploratory rules
if (length(exploratory_sorted) > 0) {

  plot(
    head(exploratory_sorted, 30),
    method = "graph",
    engine = "htmlwidget"
  )

}
# Part B: Step 3 

## Display top 3 exploratory rules
top_three <- head(exploratory_sorted, 3)

inspect(top_three)
##     lhs        rhs                 support confidence coverage lift     count
## [1] {Chips} => {Fish}              0.062   0.2952381  0.210    1.447246 31   
## [2] {Fish}  => {Chips}             0.062   0.3039216  0.204    1.447246 31   
## [3] {Bread} => {Cleaning.Supplies} 0.054   0.2872340  0.188    1.408010 27
## Alternative Display
quality(top_three)
##   support confidence coverage     lift count
## 5   0.062  0.2952381    0.210 1.447246    31
## 4   0.062  0.3039216    0.204 1.447246    31
## 9   0.054  0.2872340    0.188 1.408010    27
### Interpretation: The rule states that customers who purchase chips also have a tendency to purchase fish. The lift value of 1.447246 means that customers who buy chips are about 1.45 times more likely to purchase fish than customers in general. Since the lift here is greater than one we can determine that there is a positive association between the two items. A retailer could apply this information by placing items in close proximity or offering a combined discount.
# Part C: Step 1 -> Analyze how these association rules could inform decisions on product placement, bundling, or promotions
## Association rules can assist retailers in understanding which products are frequently purchased together. For example, it was found that Coffee and Frozen Foods were purchased together most frequently in this data set appearing together in a total of 33 transactions. Knowing that these two products are purchased together somewhat frequently retailers can organize the products in close proximity together or provide bundle deals and promotions for the two items. Lastly, retailers can better manage inventory as they can identify products that may experience a joint demand. 

# Part C: Step 2 -> Reflect on potential limitations of association rule mining (e.g., sparse data, spurious correlations)
## Association rule mining has several potential limitations some examples are sparse data, spurious correlations, no causation, threshold selection, and limited information. 
### Sparse Data: some products may appear infrequently which makes it difficult to identify meaningful purchase patterns. 
### Spurious Correlations: Some products appear together by coincidence rather than having a true relationship where the two products are commonly purchased together by shoppers. 
### No causation: Association rules may identify relationships but does not prove that purchasing one product causes a shopper to purchase the other item. 
### Threshold Selection: Using too high of a support or confidence level may cause there to be very few rules while setting them too low may provide unreliable results. 
### Limited Information: The data set does not provide information that includes customer demographics, product prices, profit margins, or purchasing motivations. 

# Part C:Step 3 -> Discuss how lift, support, and confidence metrics influence business relevance of discovered patterns
## Support demonstrates how frequently two products appear together in all of the transactions. A higher level of support indicates that the pattern occurs more frequently among customers. Lift measures how much more frequently products are purchased together compared to being purchased independently. A lift greater than 1 indicated a positive association between the two products. Lastly, confidence measures the measures the likelihood that a customer will purchase one product given that they have purchased another, the higher the confidence level is the stronger the predictive relationship is.