```{r setup, include=FALSE}
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.

## Installation

Install the released version of `arules` from CRAN:

```{r install, eval=FALSE}
install.packages("arules")
```

Load the package in each R session where you want to use it:

```{r load-package}
library(arules)
```

## Create transactions

A named list is the simplest input format for small data sets.

```{r}
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.

```{r}
summary(trans)
sort(itemFrequency(trans), decreasing = TRUE)
```

## Mine and inspect rules

`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.

```{r}
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.

```{r}
inspect(sort(rules, by = "lift"))
```

Use ordinary subsetting expressions to focus on a particular consequent or a
minimum quality value.

```{r}
butter_rules <- subset(rules, rhs %in% "butter" & lift > 1)
inspect(butter_rules)
```

## Where to learn more

For importing other data shapes, continue with
[Preparing transaction data](preparing-transaction-data.html)
(`vignette("preparing-transaction-data", package = "arules")`). For selecting
and simplifying a larger result, see
[Mining and pruning association rules](mining-and-pruning-rules.html)
(`vignette("mining-and-pruning-rules", package = "arules")`).
To explore association rules visually, see the
[`arulesViz` package](https://cran.r-project.org/package=arulesViz).
