Search code examples
rpartyj48

Getting properties values of J48


Following my question I would like to know what should I add in order to get the value of the node and to concatenate it to its name. I have a J48 decision tree:

library(RWeka) 
data(iris)
res = J48(Species ~., data = iris)
> res
J48 pruned tree
------------------

  Petal.Width <= 0.6: setosa (50.0)
Petal.Width > 0.6
|   Petal.Width <= 1.7
|   |   Petal.Length <= 4.9: versicolor (48.0/1.0)
|   |   Petal.Length > 4.9
|   |   |   Petal.Width <= 1.5: virginica (3.0)
|   |   |   Petal.Width > 1.5: versicolor (3.0/1.0)
|   Petal.Width > 1.7: virginica (46.0/1.0)

Number of Leaves  :     5

Size of the tree :  9

and get as a result the following string:

( Petal.Width ( ) Petal.Width ( Petal.Length ( ) Petal.Width ( ) ) )

I would like to get the following (concatenation of values):

( Petal.Width0.6 ( ) Petal.Width1.7 ( Petal.Length4.9 ( ) Petal.Width1.5 ( ) ) )

Here is the code I use:

library("partykit")
pres <- as.party(res)
partykit:::.list.rules.party(pres)

nam <- names(pres$data)
tr <- as.list(pres$node)
str <- "("
update_str <- function(x) {
  if(is.null(x$kids)) {
    str <<- paste(str, ")")
  } else {
    str <<- paste(str, nam[x$split$varid], "(")
    for(i in x$kids) update_str(tr[[i]])
  }
}
update_str(tr[[1]])
   > str
[1] "( Petal.Width ( ) Petal.Width ( Petal.Length ( ) Petal.Width ( ) ) )"

Solution

  • Just change the recursion:

    update_str <- function(x) {
      if(is.null(x$kids)) {
        str <<- paste(str, ")")
      } else {
        str <<- paste(str, nam[x$split$varid], x$split$breaks, "(")
        for(i in x$kids) update_str(tr[[i]])
      }
    }
    
    update_str(tr[[1]])
    
    > str
    [1] "( Petal.Width 0.6 ( ) Petal.Width 1.7 ( Petal.Length 4.9 ( ) Petal.Width 1.5 ( ) ) )"