Search code examples
rarules

How do I choose antecedent for apriori function?


How can I set the antecedent for the apriori function? I would like to recommend products for any given antecedent using the apriori rule.


Solution

  • You can generate rules ignoring the antecedent, then select the rules that match what you are looking for using the subset function.

    ## First generate rules
    library(arules)
    data(Groceries)
    rules <- apriori(Groceries, parameter = list(supp = 0.001, conf = 0.8))
    length(rules)
    [1] 410
    

    I am not sure if you want to specify the antecedent exactly or if it need only contain certain items, but you can get at either of these. Suppose the customer bought yogurt and rice. What else did they buy?

    ## antecedent contains the items
    ## irrelevant part of output removed
    inspect(subset(rules, subset = lhs %ain% c("yogurt", "rice")))
        lhs                                               rhs                
    [1] {yogurt,rice}                                  => {other vegetables} 
    [2] {root vegetables,yogurt,rice}                  => {other vegetables} 
    [3] {root vegetables,yogurt,rice}                  => {whole milk}       
    [4] {whole milk,yogurt,rice}                       => {other vegetables} 
    [5] {root vegetables,other vegetables,yogurt,rice} => {whole milk}       
    [6] {root vegetables,whole milk,yogurt,rice}       => {other vegetables} 
    [7] {other vegetables,whole milk,yogurt,rice}      => {root vegetables} 
    
    ## antecedent is completely specified
    ## irrelevant part of output removed
    inspect(subset(rules, subset = lhs %oin% c("yogurt", "rice")))
    [1] {yogurt,rice} => {other vegetables} 
    

    With subset, you can restrict the lhs (antecedent), the rhs (consequent) or what is in the full itemset. You can get more details on the help page for subset.