Search code examples
rstringtype-conversionarules

Convert rule in string format to arules in R


I have a couple of Apriori rules in string format like: (A,B) => (C) ,Support=0.1 ,Confidence=0.0

Is it possible to convert them into the same format returned by apriori function in arulesViz library, i.e a >rules object?

Format has this aspect:

   lhs                rhs         support     confidence  

[1] {A B} => {C} 0.1 0.0

PS:I cannot directly use apriori function from R since I am using a modified version of it.

Thank you Richard


Solution

  • If they are always of a similar format then the following should work.

    a <- rep('(A,B) => (C) ,Support=0.1 ,Confidence=0.0',6)
    
    b  <- matrix(unlist(strsplit(a,' ,')),ncol=3,byrow=TRUE)
    
    b[,1] <- gsub('[(]','{',b[,1])
    b[,1] <- gsub('[)]','}',b[,1])
    b[,1] <- gsub(',',' ',b[,1])
    b[,2:3] <- gsub('^.*=','',b[,2:3])
    paste(b[,1],b[,2],b[,3])
    

    I can't think of any concise way to do it but split the strings up and deal with sub-strings.