Search code examples
rsortingarules

How to sort association rules by lhs or rhs in R


I have set of rules from apriori algorithm. Sorting them by lift, confidence or support is easy:

rules.sorted = sort(rules, by="lift")

But let's say I have small set of rules with a few different rhs elements. I would like to view rules sorted by those rhs elements (alphabetically). Is there a way to do that?

I.e from this:

    lhs       rhs support   confidence lift    
1   {A}    => {B} 0.3919252 0.9431280  1.930940
2   {B}    => {A} 0.3919252 0.8024194  1.930940
3   {E,C}  => {A} 0.3535204 0.7995546  1.924047
4   {F,I}  => {F} 0.3924175 0.9005650  1.868281
5   {H}    => {G} 0.4194978 0.9659864  1.864941
6   {C,D}  => {A} 0.3653373 0.7141482  1.718525

To this:

    lhs       rhs support   confidence lift    

2   {B}    => {A} 0.3919252 0.8024194  1.930940
3   {E,C}  => {A} 0.3535204 0.7995546  1.924047
6   {C,D}  => {A} 0.3653373 0.7141482  1.718525
1   {A}    => {B} 0.3919252 0.9431280  1.930940
4   {F,I}  => {F} 0.3924175 0.9005650  1.868281
5   {H}    => {G} 0.4194978 0.9659864  1.864941

Here is an example of rules that I work with:

library(arules)
download.file("http://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data", "mush.data");
dataset = read.table("mush.data", header = F, sep=",", na.strings= "*")
tr <- as(dataset, "transactions")
param  = new("APparameter", "confidence" = 0.9, "support" = 0.7, "minlen"= 2L, "maxlen" = 2L, "target" = "rules") 
rules <-apriori(tr,param)
dput(rules)

Solution

  • Extract basic information from your rules object to a data frame, like this:

    rules_info <-
      data.frame(
        LHS = labels(lhs(rules)), 
        RHS = labels(rhs(rules)),          
        quality(rules)
      )
    

    Then sort it like a normal data frame:

    rules_info[ order(rules_info$RHS), ]