knitr::opts_chunk$set(collapse = TRUE, comment = "#>") library(arules) set.seed(1234)
Association rule mining starts with a collection of transactions. Each transaction contains a set of items, such as the products in a shopping basket. This guide introduces the basic workflow: create transactions, inspect the data, mine rules, and select useful results.
Install the released version of arules from CRAN:
install.packages("arules")
Load the package in each R session where you want to use it:
library(arules)
A named list is the simplest input format for small data sets.
baskets <- list( T1 = c("milk", "bread", "butter"), T2 = c("bread", "butter"), T3 = c("milk", "bread"), T4 = c("bread", "jam"), T5 = c("milk", "bread", "butter"), T6 = c("beer", "chips"), T7 = c("beer", "chips", "salsa"), T8 = c("bread", "butter", "jam") ) trans <- transactions(baskets) trans inspect(trans[1:3])
summary() describes the sparse transaction matrix. itemFrequency() returns
the fraction of transactions containing each item.
summary(trans) sort(itemFrequency(trans), decreasing = TRUE)
apriori() mines association rules. Support specifies how often all items in a
rule must occur together, confidence specifies how often the right-hand side
must occur when the left-hand side occurs, and maxlen limits the total number
of items in a rule.
On large data sets, setting support too low or maxlen too high can produce an
extremely large rule set and exhaust the available memory. Start with
restrictive values and relax them only as needed.
rules <- apriori( trans, parameter = list(support = 0.25, confidence = 0.6, maxlen = 5), control = list(verbose = FALSE) ) rules
Rules are often sorted by an interest measure before inspection. Lift is a common choice.
inspect(sort(rules, by = "lift"))
Use ordinary subsetting expressions to focus on a particular consequent or a minimum quality value.
butter_rules <- subset(rules, rhs %in% "butter" & lift > 1) inspect(butter_rules)
To explore association rules visually, see the
arulesViz package.
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.