Introduction to arules – A computational environment for mining association rules and frequent item sets

Mining frequent itemsets and association rules is a popular and well researched approach for discovering interesting relationships between variables in large databases. The R package arules presented in this paper provides a basic infrastructure for creating and manipulating input data sets and for analyzing the resulting itemsets and rules. The package also includes interfaces to two fast mining algorithms, the popular C implementations of Apriori and Eclat by Christian Borgelt. These algorithms can be used to mine frequent itemsets, maximal frequent itemsets, closed frequent itemsets and association rules.


Introduction
Mining frequent itemsets and association rules is a popular and well researched method for discovering interesting relations between variables in large databases.Piatetsky-Shapiro (1991) describes analyzing and presenting strong rules discovered in databases using different measures of interestingness.Based on the concept of strong rules, Agrawal, Imielinski, and Swami (1993) introduced the problem of mining association rules from transaction data as follows: Let I = {i 1 , i 2 , . . ., i n } be a set of n binary attributes called items.Let D = {t 1 , t 2 , . . ., t m } be a set of transactions called the database.Each transaction in D has an unique transaction ID and contains a subset of the items in I.A rule is defined as an implication of the form X ⇒ Y where X, Y ⊆ I and X ∩ Y = ∅.The sets of items (for short itemsets) X and Y are called antecedent (left-hand-side or LHS) and consequent (right-hand-side or RHS) of the rule.
To illustrate the concepts, we use a small example from the supermarket domain.The set of items is I = {milk, bread, butter, beer} and a small database containing the items is shown in Figure 1.An example rule for the supermarket could be {milk, bread} ⇒ {butter} meaning that if milk and bread is bought, customers also buy butter.
To select interesting rules from the set of all possible rules, constraints on various measures of

Introduction to arules
significance and interest can be used.The best-known constraints are minimum thresholds on support and confidence.The support supp(X) of an itemset X is defined as the proportion of transactions in the data set which contain the itemset.In the example database in Figure 1, the itemset {milk, bread} has a support of 2/5 = 0.4 since it occurs in 40% of all transactions (2 out of 5 transactions).
Finding frequent itemsets can be seen as a simplification of the unsupervised learning problem called "mode finding" or "bump hunting" (Hastie, Tibshirani, and Friedman 2001).For these problems each item is seen as a variable.The goal is to find prototype values so that the probability density evaluated at these values is sufficiently large.However, for practical applications with a large number of variables, probability estimation will be unreliable and computationally too expensive.This is why in practice frequent itemsets are used instead of probability estimation.
The confidence of a rule is defined conf(X ⇒ Y ) = supp(X ∪ Y )/supp(X).For example, the rule {milk, bread} ⇒ {butter} has a confidence of 0.2/0.4= 0.5 in the database in Figure 1, which means that for 50% of the transactions containing milk and bread the rule is correct.Confidence can be interpreted as an estimate of the probability P (Y |X), the probability of finding the RHS of the rule in transactions under the condition that these transactions also contain the LHS (see e.g., Hipp, Güntzer, and Nakhaeizadeh 2000).
Association rules are required to satisfy both a minimum support and a minimum confidence constraint at the same time.At medium to low support values, often a great number of frequent itemsets are found in a database.However, since the definition of support enforces that all subsets of a frequent itemset have to be also frequent, it is sufficient to only mine all maximal frequent itemsets, defined as frequent itemsets which are not proper subsets of any other frequent itemset (Zaki, Parthasarathy, Ogihara, and Li 1997b).Another approach to reduce the number of mined itemsets is to only mine frequent closed itemsets.An itemset is closed if no proper superset of the itemset is contained in each transaction in which the itemset is contained (Pasquier, Bastide, Taouil, and Lakhal 1999;Zaki 2004).Frequent closed itemsets are a superset of the maximal frequent itemsets.Their advantage over maximal frequent itemsets is that in addition to yielding all frequent itemsets, they also preserve the support information for all frequent itemsets which can be important for computing additional interest measures after the mining process is finished (e.g., confidence for rules generated from the found itemsets, or all-confidence (Omiecinski 2003)).
A practical solution to the problem of finding too many association rules satisfying the support and confidence constraints is to further filter or rank found rules using additional interest measures.A popular measure for this purpose is lift (Brin, Motwani, Ullman, and Tsur 1997).The lift of a rule is defined as lift(X ⇒ Y ) = supp(X ∪ Y )/(supp(X)supp(Y )), and transaction ID items 1 milk, bread 2 bread, butter 3 beer 4 milk, bread, butter 5 bread, butter Figure 1: An example supermarket database with five transactions.
can be interpreted as the deviation of the support of the whole rule from the support expected under independence given the supports of the LHS and the RHS.Greater lift values indicate stronger associations.
In the last decade, research on algorithms to solve the frequent itemset problem has been abundant.Goethals and Zaki (2004) compare the currently fastest algorithms.Among these algorithms are the implementations of the Apriori and Eclat algorithms by Borgelt (2003) interfaced in the arules environment.The two algorithms use very different mining strategies.Apriori, developed by Agrawal and Srikant (1994), is a level-wise, breadth-first algorithm which counts transactions.In contrast, Eclat (Zaki et al. 1997b) employs equivalence classes, depth-first search and set intersection instead of counting.The algorithms can be used to mine frequent itemsets, maximal frequent itemsets and closed frequent itemsets.The implementation of Apriori can additionally be used to generate association rules.
This paper presents arules1 , an extension package for R (R Development Core Team 2005) which provides the infrastructure needed to create and manipulate input data sets for the mining algorithms and for analyzing the resulting itemsets and rules.Since it is common to work with large sets of rules and itemsets, the package uses sparse matrix representations to minimize memory usage.The infrastructure provided by the package was also created to explicitly facilitate extensibility, both for interfacing new algorithms and for adding new types of interest measures and associations.
The rest of the paper is organized as follows: In the next section, we give an overview of the data structures implemented in the package arules.In Section 2 we introduce the functionality of the classes to handle transaction data and associations.In Section 3 we describe the way mining algorithms are interfaced in arules using the available interfaces to Apriori and Eclat as examples.In Section 4 we present some auxiliary methods for support counting, rule induction and sampling available in arules.We provide several examples in Section 5.The first two examples show typical R sessions for preparing, analyzing and manipulating a transaction data set, and for mining association rules.The third example demonstrates how arules can be extended to integrate a new interest measure.Finally, the fourth example shows how to use sampling in order to speed up the mining process.We conclude with a summary of the features and strengths of the package arules as a computational environment for mining association rules and frequent itemsets.
A previous version of this manuscript was published in the Journal of Statistical Software (Hahsler, Grün, and Hornik 2005a).

Data structure overview
To enable the user to represent and work with input and output data of association rule mining algorithms in R, a well-designed structure is necessary which can deal in an efficient way with large amounts of sparse binary data.The S4 class structure implemented in the package arules is presented in Figure 2. directly extend a common virtual class called associations which provides a common interface.In this structure it is easy to add a new type of associations by adding a new class that extends associations.
Items in associations and transactions are implemented by the itemMatrix class which provides a facade for the sparse matrix implementation ngCMatrix from the R package Matrix (Bates and Maechler 2005).
To control the behavior of the mining algorithms, the two classes ASparameter and AScontrol are used.Since each algorithm can use additional algorithm-specific parameters, we implemented for each interfaced algorithm its own set of control classes.We used the prefix 'AP' for Apriori and 'EC' for Eclat.In this way, it is easy to extend the control classes when interfacing a new algorithm.

Representing collections of itemsets
From the definition of the association rule mining problem we see that transaction databases and sets of associations have in common that they contain sets of items (itemsets) together with additional information.For example, a transaction in the database contains a transaction ID and an itemset.A rule in a set of mined association rules contains two itemsets, one for the LHS and one for the RHS, and additional quality information, e.g., values for various interest measures.
Collections of itemsets used for transaction databases and sets of associations can be represented as binary incidence matrices with columns corresponding to the items and rows corresponding to the itemsets.The matrix entries represent the presence (1) or absence (0) of Figure 3: Example of a collection of itemsets represented as a binary incidence matrix.
an item in a particular itemset.An example of a binary incidence matrix containing itemsets for the example database in Figure 1 on Page 2 is shown in Figure 3.The order in which the items are stores (i.e., the order of the columns) is called in arules the item coding and is important when working directly with the binary matrix.Note also that we need to store collections of itemsets with possibly duplicated elements (identical rows), i.e, itemsets containing exactly the same items.This is necessary, since a transaction database can contain different transactions with the same items.Such a database is still a set of transactions since each transaction also contains a unique transaction ID.
Since a typical frequent itemset or a typical transaction (e.g., a supermarket transaction) only contains a small number of items compared to the total number of available items, the binary incidence matrix will in general be very sparse with many items and a very large number of rows.A natural representation for such data is a sparse matrix format.For our implementation we chose the ngCMatrix class defined in package Matrix.The ngCMatrix is a compressed, sparse, logical, column-oriented matrix which contains the indices of the TRUE rows and the pointers to the initial indices of elements in each column of the matrix.Despite the column orientation of the ngCMatrix, it is more convenient to work with incidence matrices which are row-oriented.This makes the most important manipulation, selecting a subset of transactions from a data set for mining, more comfortable and efficient.Therefore, we implemented the class itemMatrix providing a row-oriented facade to the ngCMatrix which stores a transposed incidence matrix2 .In sparse representation the following information needs to be stored for the collection of itemsets in Figure 3: A vector of indices of the nonzero elements (row-wise starting with the first row) 1, 2, 2, 4, 1, 2, 3, 3 and the pointers 1, 3, 5, 8 where each row starts in the index vector.The first two pointers indicate that the first row starts with element one in the index vector and ends with element 2 (since with element 3 already the next row starts).The first two elements of the index vector represent the items in the first row which are i 1 and i 2 or milk and bread, respectively.The two vectors are stored in the ngCMatrix.Note that indices for the ngCMatrix start with zero rather than with one and thus actually the vectors 0, 1, 1, 3, 0, 3, 3 and 0, 3, 4, 7 are stored.However, the data structure of the ngCMatrix class is not intended to be directly accessed by the end user of arules.The interfaces of itemMatrix can be used without knowledge of how the internal representation of the data works.However, if necessary, the ngCMatrix can be directly accessed by developers to add functionality to arules (e.g., to develop new types of associations or interest measures or to efficiently compute a distance matrix between itemsets for clustering).In this case, the

Introduction to arules
ngCMatrix should be accessed using the coercion mechanism from itemMatrix to ngCMatrix via as().
In addition to the sparse matrix, itemMatrix stores item labels (e.g., names of the items) and handles the necessary mapping between the item label and the corresponding column number in the incidence matrix.Optionally, itemMatrix can also store additional information on items.For example, the category hierarchy in a supermarket setting can be stored which enables the analyst to select only transactions (or as we later see also rules and itemsets) which contain items from a certain category (e.g., all dairy products).
For itemMatrix, basic matrix operations including dim() and subset selection ([) are available.
The first element of dim() and [ corresponds to itemsets or transactions (rows), the second element to items (columns).For example, on a transaction data set in variable x the subset selection 'x[1:10, 16:20]' selects a matrix containing the first 10 transactions and items 16 to 20.
Since itemMatrix is used to represent sets or collections of itemsets additional functionality is provided.length() can be used to get the number of itemsets in an itemMatrix.Technically, length() returns the number of rows in the matrix which is equal to the first element returned by dim().Identical itemsets can be found with duplicated(), and duplicates can be removed with unique().match() can be used to find matching elements in two collections of itemsets.
With c(), several itemMatrix objects can be combined by successively appending the rows of the objects, i.e., creating a collection of itemsets which contains the itemsets from all itemMatrix objects.This operation is only possible if the itemMatrix objects employed are "compatible," i.e., if the matrices have the same number of columns and the items are in the same order.If two objects contain the same items (item labels), but the order in the matrix is different or one object is missing some items, recode() can be used to make them compatible by reordering and inserting columns.
To get the actual number of items in the itemsets stored in the itemMatrix, size() is used.
It returns a vector with the number of items (ones) for each element in the set (row sum in the matrix).Obtaining the sizes from the sparse representations is a very efficient operation, since it can be calculated directly from the vector of column pointers in the ngCMatrix.
For a purchase incidence matrix, size() will produce a vector as long as the number of transactions in the matrix with each element of the vector containing the number of items in the corresponding transaction.This information can be used, e.g., to select or filter unusually long or short transactions.
itemFrequency() calculates the frequency for each item in an itemMatrix.Conceptually, the item frequencies are the column sums of the binary matrix.Technically, column sums can be implemented for sparse representation efficiently by just tabulating the vector of row numbers of the non-zero elements in the ngCMatrix.Item frequencies can be used for many purposes.For example, they are needed to compute interest measures.itemFrequency() is also used by itemFrequencyPlot() to produce a bar plot of item count frequencies or support.Such a plot gives a quick overview of a set of itemsets and shows which are the most important items in terms of occurrence frequency.
Coercion from and to matrix and list primitives is provided where names and dimnames are used as item labels.For the coercion from itemMatrix to list there are two possibilities.The usual coercion via as() results in a list of vectors of character strings, each containing the item labels of the items in the corresponding row of the itemMatrix.The actual conversion is items milk bread butter beer done by LIST() with its default behavior (argument decode set to TRUE).If in turn LIST() is called with the argument decode set to FALSE, the result is a list of integer vectors with column numbers for items instead of the item labels.For many computations it is useful to work with such a list and later use the item column numbers to go back to the original itemMatrix for, e.g., subsetting columns.For subsequently decoding column numbers to item labels, decode() is also available.
Finally, image() can be used to produce a level plot of an itemMatrix which is useful for quick visual inspection.For transaction data sets (e.g., point-of-sale data) such a plot can be very helpful for checking whether the data set contains structural changes (e.g., items were not offered or out-of-stock during part of the observation period) or to find abnormal transactions (e.g., transactions which contain almost all items may point to recording problems).Spotting such problems in the data can be very helpful for data preparation.

Transaction data
The main application of association rules is for market basket analysis where large transaction data sets are mined.In this setting each transaction contains the items which were purchased at one visit to a retail store (see e.g., Berry and Linoff 1997).Transaction data are normally recorded by point-of-sale scanners and often consists of tuples of the form: All tuples with the same transaction ID form a single transaction which contains all the items given by the item IDs in the tuples.Additional information denoted by the ellipsis dots might be available.For example, a customer ID might be provided via a loyalty program in a supermarket.Further information on transactions (e.g., time, location), on the items (e.g., category, price), or on the customers (socio-demographic variables such as age, gender, etc.) might also be available.
For mining, the transaction data is first transformed into a binary purchase incidence matrix with columns corresponding to the different items and rows corresponding to transactions.The matrix entries represent the presence (1) or absence (0) of an item in a particular transaction.This format is often called the horizontal database layout (Zaki 2000).Alternatively,

Introduction to arules
transaction data can be represented in a vertical database layout in the form of transaction ID lists (Zaki 2000).In this format for each item a list of IDs of the transactions the item is contained in is stored.In Figure 4 the example database in Figure 1 on Page 2 is depicted in horizontal and vertical layouts.Depending on the algorithm, one of the layouts is used for mining.In arules both layouts are implemented as the classes transactions and tidLists.Similar to transactions, class tidLists also uses a sparse representation to store its lists efficiently.Objects of classes transactions and tidLists can be directly converted into each other by coercion.
The class transactions directly extends itemMatrix and inherits its basic functionality (e.g., subset selection, getting itemset sizes, plotting item frequencies).In addition, transactions has a slot to store further information for each transaction in form of a data.frame.The slot can hold arbitrary named vectors with length equal to the number of stored transactions.In arules the slot is currently used to store transaction IDs, however, it can also be used to store user IDs, revenue or profit, or other information on each transaction.With this information subsets of transactions (e.g., only transactions of a certain user or exceeding a specified profit level) can be selected.
Objects of class transactions can be easily created by coercion from matrix or list.If names or dimnames are available in these data structures, they are used as item labels or transaction IDs, accordingly.To import data from a file, the read.transactions()function is provided.This function reads files structured as shown in Figure 4 and also the very common format with one line per transaction and the items separated by a predefined character.Finally, inspect() can be used to inspect transactions (e.g., "interesting" transactions obtained with subset selection).
Another important application of mining association rules has been proposed by Piatetsky-Shapiro (1991) and Srikant and Agrawal (1996) for discovering interesting relationships between the values of categorical and quantitative (metric) attributes.For mining associations rules, non-binary attributes have to be mapped to binary attributes.The straightforward mapping method is to transform the metric attributes into k ordinal attributes by building categories (e.g., an attribute income might be transformed into a ordinal attribute with the three categories: "low", "medium" and "high").Then, in a second step, each categorical attribute with k categories is represented by k binary dummy attributes which correspond to the items used for mining.An example application using questionnaire data can be found in Hastie et al. (2001) in the chapter about association rule mining.
The typical representation for data with categorical and quantitative attributes in R is a data.frame.First, a domain expert has to create useful categories for all metric attributes.This task is supported in arules by functions such as discretize() and discretizeDF() which implement equal interval length, equal frequency, clustering-based and custom interval discretization.After discretization all columns in the data.frameneed to be either logical or factors.The second step, the generation of binary dummy items, is automated in package arules by coercing from data.frame to transactions.In this process, the original attribute names and categories are preserved as additional item information and can be used to select itemsets or rules which contain items referring to a certain original attributes.By default it is assumed that missing values do not carry information and thus all of the corresponding dummy items are set to zero.If the fact that the value of a specific attribute is missing provides information (e.g., a respondent in an interview refuses to answer a specific question), the domain expert can create for the attribute a category for missing values which then will be included in the transactions as its own dummy item.
The resulting transactions object can be mined and analyzed the same way as market basket data, see the example in Section 5.1.

Associations: itemsets and sets of rules
The result of mining transaction data in arules are associations.Conceptually, associations are sets of objects describing the relationship between some items (e.g., as an itemset or a rule) which have assigned values for different measures of quality.Such measures can be measures of significance (e.g., support), or measures of interestingness (e.g., confidence, lift), or other measures (e.g., revenue covered by the association).
All types of association have a common functionality in arules comprising the following methods: • summary() to give a short overview of the set and inspect() to display individual associations, • length() for getting the number of elements in the set, • items() for getting for each association a set of items involved in the association (e.g., the union of the items in the LHS and the RHS for each rule), • sorting the set using the values of different quality measures (sort()), • subset extraction ([ and subset()), • set operations (union(), intersect() and setequal()), and • matching elements from two sets (match()), • write() for writing associations to disk in human readable form.To save and load associations in compact form, use save() and load() from the base package.
The associations currently implemented in package arules are sets of itemsets (e.g., used for frequent itemsets of their closed or maximal subset) and sets of rules (e.g., association rules).Both classes, itemsets and rules, directly extend the virtual class associations and provide the functionality described above.
Class itemsets contains one itemMatrix object to store the items as a binary matrix where each row in the matrix represents an itemset.In addition, it may contain transaction ID lists as an object of class tidLists.Note that when representing transactions, tidLists store for each item a transaction list, but here store for each itemset a list of transaction IDs in which the itemset appears.Such lists are currently only returned by eclat().
Class rules consists of two itemMatrix objects representing the left-hand-side (LHS) and the right-hand-side (RHS) of the rules, respectively.
The items in the associations and the quality measures can be accessed and manipulated in a safe way using accessor and replace methods for items, lhs, rhs, and quality.In addition

Introduction to arules
the association classes have built-in validity checking which ensures that all elements have compatible dimensions.
It is simple to add new quality measures to existing associations.Since the quality slot holds a data.frame,additional columns with new quality measures can be added.These new measures can then be used to sort or select associations using sort() or subset().Adding a new type of associations to arules is straightforward as well.To do so, a developer has to create a new class extending the virtual associations class and implement the common functionality described above.

Mining algorithm interfaces
In package arules we interface free reference implementations of Apriori and Eclat by Christian Borgelt (Borgelt and Kruse 2002;Borgelt 2003) 3 .The code is called directly from R by the functions apriori() and eclat() and the data objects are directly passed from R to the C code and back without writing to external files.The implementations can mine frequent itemsets, and closed and maximal frequent itemsets.In addition, apriori() can also mine association rules.
The data given to the apriori() and eclat() functions have to be transactions or something which can be coerced to transactions (e.g., matrix or list).The algorithm parameters are divided into two groups represented by the arguments parameter and control.The mining parameters (parameter) change the characteristics of the mined itemsets or rules (e.g., the minimum support) and the control parameters (control) influence the performance of the algorithm (e.g., enable or disable initial sorting of the items with respect to their frequency).These arguments have to be instances of the classes APparameter and APcontrol for the function apriori() or ECparameter and ECcontrol for the function eclat(), respectively.Alternatively, data which can be coerced to these classes (e.g., NULL which will give the default values or a named list with names equal to slot names to change the default values) can be passed.In these classes, each slot specifies a different parameter and the values.The default values are equal to the defaults of the stand-alone C programs (Borgelt 2004) except that the standard definition of the support of a rule (Agrawal et al. 1993) is employed for the specified minimum support required (Borgelt defines the support of a rule as the support of its antecedent).
For apriori() the appearance feature implemented by Christian Borgelt can also be used.
With argument appearance of function apriori() one can specify which items have to or must not appear in itemsets or rules.For more information on this feature we refer to the Apriori manual (Borgelt 2004).
The output of the functions apriori() and eclat() is an object of a class extending associations which contains the sets of mined associations and can be further analyzed using the functionality provided for these classes.
There exist many different algorithms which which use an incidence matrix or transaction ID list representation as input and solve the frequent and closed frequent itemset problems.Each algorithm has specific strengths which can be important for very large databases.Such algorithms, e.g.kDCI, LCM, FP-Growth or Patricia, are discussed in Goethals and Zaki (2003).The source code of most algorithms is available on the internet and, if a special algorithm is needed, interfacing the algorithms for arules is straightforward.The necessary steps are: 1. Adding interface code to the algorithm, preferably by directly calling into the native implementation language (rather than using files for communication), and an R function calling this interface.

Auxiliary functions
In arules several helpful functions are implemented for support counting, rule induction, sampling, etc.In the following we will discuss some of these functions.

Counting support for itemsets
Normally, itemset support is counted during mining the database with a given minimum support constraint.During this process all frequent itemsets plus some infrequent candidate itemsets are counted (or support is determined by other means).Especially for databases with many items and for low minimum support values, this procedure can be extremely time consuming since in the worst case, the number of frequent itemsets grows exponentially in the number of items.
If only the support information for a single or a few itemsets is needed, we might not want to mine the database for all frequent itemsets.We also do not know in advance how high (or low) to set the minimum support to still get the support information for the itemsets in question.For this problem, arules contains support() which determines the support for a set of given sets of items (as an itemMatrix).
For counting, we use a prefix tree (Knuth 1997) to organize the counters.The used prefix tree is similar to the itemset tree described by Borgelt and Kruse (2002).However, we do not generate the tree level-wise, but we first generate a prefix tree which only contains the nodes necessary to hold the counters for all itemsets which need to be counted.Using the nodes in this tree only, we count the itemsets for each transaction recursively.After counting, the support for each itemset is contained in the node with the prefix equal to the itemset.The exact procedure is described in Hahsler, Buchta, and Hornik (2008).
In addition to determining the support of a few itemsets without mining all frequent itemsets, support() is also useful for finding the support of infrequent itemsets with a support so low that mining is infeasible due to combinatorial explosion.

Rule induction
For convenience we introduce X = {X 1 , X 2 , . . ., X l } for sets of itemsets with length l.Analogously, we write R for sets of rules.A part of the association rule mining problem is the generation (or induction) of a set of rules R from a set of frequent itemsets X .The implementation of the Apriori algorithm used in arules already contains a rule induction engine and by default returns the set of association rules of the form X ⇒ Y which satisfy given

Introduction to arules
minimum support and minimum confidence.Following the definition of Agrawal et al. (1993) Y is restricted to single items.
In some cases it is necessary to separate mining itemsets and generating rules from itemsets.For example, only rules stemming from a subset of all frequent itemsets might be of interest to the user.The Apriori implementation efficiently generates rules by reusing the data structures built during mining the frequent itemsets.However, if Apriori is used to return only itemsets or Eclat or some other algorithm is used to mine itemsets, the data structure needed for rule induction is no longer available for computing rule confidence.
If rules need to be induced from an arbitrary set of itemsets, support values required to calculate confidence are typically missing.For example, if all available information is an itemset containing five items and we want to induce rules, we need the support of the itemset (which we might know), but also the support of all subsets of length four.The missing support information has to be counted from the database.Finally, to induce rules efficiently for a given set of itemsets, we also have to store support values in a suitable data structure which allows fast look-ups for calculating rule confidence.
Function ruleInduction() provided in arules uses a prefix tree to induce rules for a given confidence from an arbitrary set of itemsets X in the following way: 1. Count the support values for each itemset X ∈ X and the subsets {X \ {x} : x ∈ X} needed for rule generation in a single pass over the database and store them in a suitable data structure.
2. Populate set R by selectively generating only rules for the itemsets in X using the support information from the data structure created in step 1.
Efficient support counting is done as described in Section 4.1 above.After counting, all necessary support counts are contained in the prefix tree.We can retrieve the needed support values and generating the rules is straight forward.The exact procedure is described in Hahsler et al. (2008).

Sampling from transactions
Taking samples from large databases for mining is a powerful technique which is especially useful if the original database does not fit into main memory, but the sample does.However, even if the database fits into main memory, sampling can provide an enormous speed-up for mining at the cost of only little degradation of accuracy.Mannila, Toivonen, and Verkamo (1994) proposed sampling with replacement for association rule mining and quantify the estimation error due to sampling.Using Chernov bounds on the binomial distribution (the number of transactions which contains a given itemset in a sample), the authors argue that in theory even relatively small samples should provide good estimates for support.
Zaki, Parthasarathy, Li, and Ogihara (1997a) built upon the theoretic work by Mannila et al. (1994) and show that for an itemset X with support τ = supp(X) and for an acceptable relative error of support ϵ (an accuracy of 1 − ϵ) at a given confidence level 1 − c, the needed sample size n can be computed by Depending on its support, for each itemset a different sample size is appropriate.As a heuristic, the authors suggest to use the user specified minimum support threshold for τ .This means that for itemsets close to minimum support, the given error and confidence level hold while for more frequent itemsets the error rate will be less.However, with this heuristic the error rate for itemsets below minimum support can exceed ϵ at the given confidence level and thus some infrequent itemsets might appear as frequent ones in the sample.Zaki et al. (1997a) also evaluated sampling in practice on several data sets and conclude that sampling not only speeds mining up considerably, but also the errors are considerably smaller than those given by the Chernov bounds and thus samples with size smaller than obtained by Equation 1 are often sufficient.
Another way to obtain the required sample size for association rule mining is progressive sampling (Parthasarathy 2002).This approach starts with a small sample and uses progressively larger samples until model accuracy does not improve significantly anymore.Parthasarathy (2002) defines a proxy for model accuracy improvement by using a similarity measure between two sets of associations.The idea is that since larger samples will produce more accurate results, the similarity between two sets of associations of two consecutive samples is low if accuracy improvements are high and increases with decreasing accuracy improvements.Thus increasing sample size can be stopped if the similarity between consecutive samples reaches a "plateau."Toivonen (1996) presents an application of sampling to reduce the needed I/O overhead for very large databases which do not fit into main memory.The idea is to use a random sample from the data base to mine frequent itemsets at a support threshold below the set minimum support.The support of these itemsets is then counted in the whole database and the infrequent itemsets are discarded.If the support threshold to mine the sample is picked low enough, almost all frequent itemsets and their support will be found in one pass over the large database.
In arules sampling is implemented by sample() which provides all capabilities of the standard sampling function in R (e.g., sampling with or without replacement and probability weights).

Generating synthetic transaction data
Synthetic data can be used to evaluate and compare different mining algorithms and to study the behavior of measures of interestingness.
In arules the function random.transactions()can be used to create synthetic transaction data.Currently there are two methods available.The first method reimplements the well known generator for transaction data for mining association rules developed by Agrawal and Srikant (1994).The second method implements a simple probabilistic model where each transaction is the result of one independent Bernoulli trial for each item (see (Hahsler, Hornik, and Reutterer 2005b)).

Sub-, super-, maximal and closed itemsets
For some calculations it is necessary to find all sub-or supersets for a specific itemset in a Introduction to arules set of itemsets.This functionality is implemented as is.subset() and is.superset().For example, is.subset(x, y, proper = TRUE), finds all proper subsets of the itemsets in x in the set y.The result is a logical matrix with length(x) rows and length(y) columns.Each logical row vector represents which elements in y are subsets of the corresponding element in x.If y is omitted, the sub-or superset structure within the set x is returned.Similar methods, is.maximal() and is.closed(), can be used to find all maximal itemsets or closed itemsets in a set.An itemset is maximal in a set if no proper superset of the itemset is contained in the set (Zaki et al. 1997b).An itemset is closed, if it is its own closure (i.e., for an items no superset with the same support exits) (Pasquier et al. 1999).
Note that these methods can be extremely slow and have high memory usage if the set contains many itemsets.

Additional measures of interestingness
arules provides interestMeasure() which can be used to calculate a broad variety of interest measures for itemsets and rules.To speed up the calculation, we try to reuse the quality information available from the sets of itemsets or rules (i.e., support, confidence, lift) and, only if necessary, missing information is obtained from the transactions used to mine the associations.

Distance based clustering transactions and associations
To allow for distance based clustering (Gupta, Strehl, and Ghosh 1999), arules provides dissimilarity() which can be used to calculate dissimilarities and cross-dissimilarities between transactions or associations (i.e., itemsets and rules).Currently, the following standard measures for binary data are available: Jaccard coefficient, simple matching coefficient and dice coefficient.Additionally, dissimilarity between transactions can be calculated based on affinities between items (Aggarwal, Procopiuc, and Yu 2002).
The result of dissimilarity() is either a dist object, which can be directly used by most clustering methods in R (e.g., hclust for hierarchical clustering), or an object of class ar_cross_dissimilarity.
Since the number of transactions or associations in often too large to efficiently calculate a dissimilarity matrix and apply a clustering algorithm, sample() can be used to cluster only a subset of transactions (associations).To assign the remaining transactions (associations) to clusters, predict() implements the nearest neighbor approach for predicting memberships for new data.
A small example can be found in Hahsler and Hornik (2007a).

Support for Item Hierarchies
Often an item hierarchy is available for datasets used for association rule mining.For example in a supermarket dataset items like "bread" and "beagle" might belong to the item group (category) "baked goods."Transactions can store item hierarchies as additional columns in the itemInfo data.frame.arules provides support to use an item hierarchy to perform analysis at a group level of the item hierarchy using aggregate(), and to perform multi-level analysis to uncover relationships between individual items and item groups with addAggregate().
See ?hierarchy for details and examples.

Item Coding
Several applications require taking care of how the items are represented in the binary matrices used in transactions and associations.The order in which items are used as columns in objects of class itemMatrix is called in arules the item coding.Situations where consistent item coding is important include: • Mining several different data sets or different subsets of a data set (e.g., samples) and performing computations on the resulting associations (e.g., comparing or combining rules).
• Creating transactions, itemsets or association rules manually.
The item coding is typically determined when data is coerced to transactions with transactions(x) or as(x, "transactions") and this process can lead to different item codings for slightly different data sets.The methods encode() and recode() can be used to create and change the item coding to make the representation of transactions, itemsets and rules compatible.
To check if two objects use the same item coding, method compatible() can be used.
More information and examples on item coding can be found in the manual page ?itemCoding.

Example 1: Analyzing and preparing a transaction data set
In this example, we show how a data set can be analyzed and manipulated before associations are mined.This is important for finding problems in the data set which could make the mined associations useless or at least inferior to associations mined on a properly prepared data set.
For the example, we look at the Epub transaction data contained in package arules.summary() displays the most frequent items in the data set, information about the transaction length distribution and that the data set contains some extended transaction information.We see that the data set contains transaction IDs and in addition time stamps (using class POSIXct) for the transactions.This additional information can be used for analyzing the data set.For 2003, the first year in the data set, we have 987 transactions.We can select the corresponding transactions and inspect the structure using a level-plot (see Figure 5).

> image(Epub2003)
The plot is a direct visualization of the binary incidence matrix where the the dark dots represent the ones in the matrix.From the plot we see that the items in the data set are not evenly distributed.In fact, the mostly white area to the right side suggests, that in the beginning of 2003 only very few items were available (less than 50) and then during the year more items were added until it reached a number of around 300 items.Also, we can see that there are some transactions in the data set which contain a very high number of items (denser horizontal lines).These transactions need further investigation since they could originate from data collection problems (e.g., a web robot downloading many documents from the publication site).To find the very long transactions we can use the size() and select very long transactions (containing more than 20 items).We found three long transactions and printed the corresponding transaction information.Of course, size can be used in a similar fashion to remove long or short transactions.

Introduction to arules
Transactions can be inspected using inspect().Since the long transactions identified above would result in a very long printout, we will inspect the first 5 transactions in the subset for 2003.Most transactions contain one item.Only transaction 4 contains three items.For further inspection transactions can be converted into a list with:

> inspect(Epub2003[1:5])
Finally, transaction data in horizontal layout can be converted to transaction ID lists in vertical layout using coercion.

> EpubTidLists <-as(Epub, "tidLists") > EpubTidLists
tidLists in sparse format with 936 items/itemsets (rows) and 15729 transactions (columns) For performance reasons the transaction ID list is also stored in a sparse matrix.To get a list, coercion to list can be used.
In the next example, we will see how a data set is created and rules are mined.

Example 2: Preparing and mining a questionnaire data set
As a second example, we prepare and mine questionnaire data.We use the Adult data set from the UCI machine learning repository (Asuncion and Newman 2007) provided by package arules.This data set is similar to the marketing data set used by Hastie et al. (2001) in their chapter about association rule mining.The data originates from the U.S. census bureau database and contains 48842 instances with 14 attributes like age, work class, education, etc.In the original applications of the data, the attributes were used to predict the income level of individuals.We added the attribute income with levels small and large, representing an income of ≤ USD 50,000 and > USD 50,000, respectively.This data is included in arules as a data.frame the data set AdultUCI.

> data("AdultUCI") > dim(AdultUCI)
[1] 48842 15 AdultUCI contains a mixture of categorical and metric attributes and needs some preparations before it can be transformed into transaction data suitable for association mining.
While the apriori function will try to convert the data.frame to transactions by performing discretization of numbers, it is typically preferred to prepare the data and coerce the dataset into transactions manually.
First, we remove the two attributes fnlwgt and education-num.The first attribute is a weight calculated by the creators of the data set from control data provided by the Population Division of the U.S. census bureau.The second removed attribute is just a numeric representation of the attribute education which is also part of the data set.

> AdultUCI[["fnlwgt"]] <-NULL > AdultUCI[["education-num"]] <-NULL
Next, we need to map the four remaining metric attributes (age, hours-per-week, capital-gain and capital-loss) to ordinal attributes by building suitable categories.We divide the attributes age and hours-per-week into suitable categories using knowledge about typical age groups and working hours.For the two capital related attributes, we create a category called None for cases which have no gains/losses.Then we further divide the group with gains/losses at their median into the two categories Low and High.

> Adult <-transactions(AdultUCI) > Adult
transactions in sparse format with 48842 transactions (rows) and 115 items (columns) The remaining categorical attributes were automatically recoded into binary items.During encoding the item labels were generated in the form of <variable name >=<category label >.Note that for cases with missing values all items corresponding to the attributes with the missing values were set to zero.The summary of the transaction data set gives a rough overview showing the most frequent items, the length distribution of the transactions and the extended item information which shows which variable and which value were used to create each binary item.In the first example we see that the item with label age=Middle-aged was generated by variable age and level middle-aged.

> summary(Adult
To see which items are important in the data set we can use the itemFrequencyPlot().To reduce the number of items, we only plot the item frequency for items with a support greater than 10% (using the parameter support).For better readability of the labels, we reduce the label size with the parameter cex.names.The plot is shown in Figure 6.
> itemFrequencyPlot (Adult,support = 0.1,cex.names=0.8)Next, we call the function apriori() to find all rules (the default association type for apriori()) with a minimum support of 1% and a confidence of 0.6.

> rules set of 276443 rules
First, the function prints the used parameters.Apart from the specified minimum support and minimum confidence, all parameters have the default values.It is important to note that with parameter maxlen, the maximum size of mined frequent itemsets, is by default restricted to 5. Longer association rules are only mined if maxlen is set to a higher value.
After the parameter settings, the output of the C implementation of the algorithm with timing information is displayed.
The result of the mining algorithm is a set of 276443 rules.For an overview of the mined rules summary() can be used.It shows the number of rules, the most frequent items contained in the left-hand-side and the right-hand-side and their respective length distributions and summary statistics for the quality measures returned by the mining algorithm.
> summary(rules) From the rules we see that workers in the private sector working part-time or in the service industry tend to have a small income while persons with high capital gain who are born in the US tend to have a large income.This example shows that using subset selection and sorting a set of mined associations can be analyzed even if it is huge.
Finally, the found rules can be written to disk to be shared with other applications.To save rules in plain text format the function write() is used.The following command saves a set of rules as the file named 'data.csv'in comma separated value (CSV) format.
> write(rulesIncomeSmall, file = "data.csv",sep = ",", col.names = NA) Alternatively, with package pmml (Williams 2008) the rules can be saved in PMML (Predictive Modelling Markup Language), a standardized XML-based representation used my many data mining tools.Note that pmml requires the package XML which might not be available for all operating systems.

> write.PMML(rulesIncomeSmall, file = "data.xml")
The saved data can now be easily shared and used by other applications.Itemsets (with write() also transactions) can be written to a file in the same way.

Example 3: Extending arules with a new interest measure
In this example, we show how easy it is to add a new interest measure, using all-confidence as introduced by Omiecinski (2003).The all-confidence of an itemset X is defined as all-confidence(X) = supp(X) max I⊂X supp(I) (2) This measure has the property conf(I ⇒ X \I) ≥ all-confidence(X) for all I ⊂ X.This means that all possible rules generated from itemset X must at least have a confidence given by the itemset's all-confidence value.Omiecinski (2003) shows that the support in the denominator of equation 2 must stem from a single item and thus can be simplified to max i∈X supp({i}).
To obtain an itemset to calculate all-confidence for, we mine frequent itemsets from the previously used Adult data set using the Eclat algorithm.
> data("Adult") > fsets <-eclat(Adult, parameter = list(support = 0.05), + control = list(verbose=FALSE)) For the denominator of all-confidence we need to find all mined single items and their corresponding support values.In the following we create a named vector where the names are the column numbers of the items and the values are their support.Next, we can calculate the all-confidence using Equation 2 for all itemsets.The single item support needed for the denomination is looked up from the named vector singleSupport and the resulting measure is added to the set's quality data frame.

> summary(fsets)
[1] 0.3572453 [2] 0.3570388 [3] 0.3445408 The resulting itemsets show that the item high school graduate (but no higher education) is highly associated with working full-time, a small income and working in the private sector.All-confidence is along with many other measures of interestingness already implemented in arules as the function interestMeasure().

Example 4: Sampling
In this example, we show how sampling can be used in arules.We use again the Adult data set.

> data("Adult") > Adult
transactions in sparse format with 48842 transactions (rows) and 115 items (columns) To calculate a reasonable sample size n, we use the formula developed by Zaki et al. (1997a) and presented in Section 4.3.We choose a minimum support of 5%.As an acceptable error rate for support ϵ we choose 10% and as the confidence level (1 − c) we choose 90%.
The resulting sample size is considerably smaller than the size of the original database.With sample() we produce a sample of size n with replacement from the database.

> AdultSample <-sample(Adult, n, replace = TRUE)
The sample can be compared with the database (the population) using an item frequency plot.The item frequencies in the sample are displayed as bars and the item frequencies in the original database are represented by the line.For better readability of the labels, we only display frequent items in the plot and reduce the label size with the parameter cex.names.The plot is shown in Figure 7.Alternatively, a sample can be compared with the population using the lift ratio (with lift = TRUE).The lift ratio for each item i is P (i|sample)/P (i|population) where the probabilities are estimated by the item frequencies.A lift ratio of one indicates that the items occur in the sample in the same proportion as in the population.A lift ratio greater than one indicates that the item is over-represented in the sample and vice versa.With this plot, large relative deviations for less frequent items can be identified visually (see Figure 8).
> itemFrequencyPlot(AdultSample, population = Adult, + support = supp, lift = TRUE, + cex.names = 0.9) To compare the speed-up reached by sampling we use the Eclat algorithm to mine frequent itemsets on both, the database and the sample and compare the system time (in seconds) used for mining.
> time <-system.time(itemsets <-eclat(Adult, + parameter = list(support = supp), control = list(verbose = FALSE))) > time user system elapsed 0.061 0.000 0.063 The first element of the vector returned by system.time()gives the (user) CPU time needed for the execution of the statement in its argument.Therefore, mining the sample instead of the whole data base results in a speed-up factor of: user.self 4.357143 To evaluate the accuracy for the itemsets mined from the sample, we analyze the difference between the two sets.

Introduction to arules
> itemsetsSample set of 8651 itemsets The two sets have roughly the same size.To check if the sets contain similar itemsets, we match the sets and see what fraction of frequent itemsets found in the database were also found in the sample.
> match <-match(itemsets, itemsetsSample, nomatch = 0) > ## remove no matches > sum(match > 0) / length(itemsets) [1] 0.9843456 Almost all frequent itemsets were found using the sample.The summaries of the support of the frequent itemsets which were not found in the sample and the itemsets which were frequent in the sample although they were infrequent in the database, respectively, give: This shows that only itemsets with support very close to the minimum support were falsely missed or found.
For the frequent itemsets which were found in the database and in the sample, we can calculate accuracy from the the error rate.

Summary and outlook
With package arules we provide the basic infrastructure which enables us to mine associations and analyze and manipulate the results.Previously, in R there was no such infrastructure available.The main features of arules are: • Efficient implementation using sparse matrices.
• Simple and intuitive interface to manipulate and analyze transaction data, sets of itemsets and rules with subset selection and sorting.
• Interface to two fast mining algorithms.
• Flexibility in terms of adding new quality measures, and additional item and transaction descriptions which can be used for selecting transactions and analyzing resulting associations.
• Extensible data structure to allow for easy implementation of new types of associations and interfacing new algorithms.
There are several interesting possibilities to extend arules.For example, it would be very useful to interface algorithms which use statistical measures to find "interesting" itemsets (which are not necessarily frequent itemsets as used in an association rule context).Such algorithms include implementations of the χ 2 -test based algorithm by Silverstein, Brin, and Motwani (1998) or the baseline frequency approach by DuMouchel and Pregibon (2001).Also, the implementation of distance based clustering in arules could be used for visualization of associations (see e.g., Strehl and Ghosh 2003).

Figure 4 :
Figure 4: Example of a set of transactions represented in (a) horizontal layout and in (b) vertical layout.

Figure 6 :
Figure 6: Item frequencies of items in the Adult data set with support greater than 10%.

Figure 7 :
Figure 7: Item frequencies in a sample of the Adult data set (bars) compared to the complete data set (line).

Figure 8 :
Figure 8: Deviations of the item frequencies in the sample from the complete Adult data set.
This data set contains downloads of documents from the Electronic Publication platform of the Vienna University of Economics and Business available via http://epub.wu-wien.ac.at from January 2003 to December 2008.First, we load arules and the data set.