Desktop Survival Guide
by Graham Williams

Convert Tree to Rules

list.rules.rpart <- function(model)
  if (!inherits(model, "rpart")) stop("Not a legitimate rpart tree")
  # Get some information.
  frm     <- model$frame
  names   <- row.names(frm)
  ylevels <- attr(model, "ylevels")
  ds.size <- model$frame[1,]$n
  # Print each leaf node as a rule.
  for (i in 1:nrow(frm))
    if (frm[i,1] == "<leaf>")
      # The following [,5] is hardwired - needs work!
      cat(sprintf(" Rule number: %s ", names[i]))
      cat(sprintf("[yval=%s cover=%d (%.0f%%) prob=%0.2f]\n",
                  ylevels[frm[i,]$yval], frm[i,]$n,
                  round(100*frm[i,]$n/ds.size), frm[i,]$yval2[,5]))
      pth <- path.rpart(model, nodes=as.numeric(names[i]),
      cat(sprintf("   %s\n", unlist(pth)[-1]), sep="")

Copyright © Togaware Pty Ltd
Support further development through the purchase of the PDF version of the book.
The PDF version is a formatted comprehensive draft book (with over 800 pages).
Brought to you by Togaware. This page generated: Sunday, 22 August 2010