Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

r - Sorting rules by lift and confidence

I am trying to find association rules using the apriori function from arules package in R.

rules <- apriori(data=data, parameter=list(supp=0.001,conf = 0.08), 
                  appearance = list(default="lhs",rhs="YOGHURT"),
                  control = list(verbose=F))

rules <- sort(rules, decreasing=TRUE,by="confidence")

inspect(rules[1:3])


    lhs       rhs      support      confidence       lift
1. {A,B}     {C}       0.04           0.96           0.25
2. {C,A}     {D}       0.05           0.95           0.26
3. {B,D}     {A,C}     0.03           0.93           0.24

With the code showed above I got some association rules saved in the variable "rules" ordered by confidence in a decreasing way. But I would like to order these rules by confidence and by lift at the same time. I tried this but I got an error:

rules <- sort(rules, decreasing=TRUE,by=c("confidence","lift"))

Error in .subset2(x, i, exact = exact) : subscript out of bounds

Is there a way to sort rules by confidence and lift at the same time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have not thought about this. You can copy & paste the following code into your R session after you load arules.

setMethod("sort", signature(x = "associations"),
  function (x, decreasing = TRUE, na.last = NA, by = "support", ...) {
    q <- quality(x)
    q <- q[, pmatch(by, colnames(q)), drop = FALSE]
    if(is.null(q)) stop("Unknown interest measure to sort by.")
    if(length(x) == 0) return(x)

    x[do.call(order, c(q, list(na.last = na.last, decreasing = decreasing)))]
}) 

Now your original code should work.

> data("Adult")
> rules <- apriori(Adult, parameter = list(supp = 0.5, conf = 0.9, target = "rules"))
> inspect(head(sort(rules, by=c("supp", "conf"))))
  lhs                               rhs                   support confidence      lift
1 {}                             => {capital-loss=None} 0.9532779  0.9532779 1.0000000
2 {}                             => {capital-gain=None} 0.9173867  0.9173867 1.0000000
3 {capital-gain=None}            => {capital-loss=None} 0.8706646  0.9490705 0.9955863
4 {capital-loss=None}            => {capital-gain=None} 0.8706646  0.9133376 0.9955863
5 {native-country=United-States} => {capital-loss=None} 0.8548380  0.9525461 0.9992323
6 {native-country=United-States} => {capital-gain=None} 0.8219565  0.9159062 0.9983862

This will be part of the next release of arules.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...