Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print decision tree in text nicely / with custom control [r]

I'd like to print a decision tree in text nicely. For example, I can print the tree object itself:

library(rpart)

f = as.formula('Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species')
fit = rpart(f, data = iris, control = rpart.control(xval = 3))

fit

yields

n= 150 

node), split, n, deviance, yval
      * denotes terminal node

 1) root 150 102.1683000 5.843333  
   2) Petal.Length< 4.25 73  13.1391800 5.179452  
     4) Petal.Length< 3.4 53   6.1083020 5.005660  
       8) Sepal.Width< 3.25 20   1.0855000 4.735000 *
       9) Sepal.Width>=3.25 33   2.6696970 5.169697 *
... # omitted

partykit prints it neater:

library(partykit)

as.party(fit)

yields

Model formula:
Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species

Fitted party:
[1] root
|   [2] Petal.Length < 4.25
|   |   [3] Petal.Length < 3.4
|   |   |   [4] Sepal.Width < 3.25: 4.735 (n = 20, err = 1.1)
|   |   |   [5] Sepal.Width >= 3.25: 5.170 (n = 33, err = 2.7)
|   |   [6] Petal.Length >= 3.4: 5.640 (n = 20, err = 1.2)
...# omitted

Number of inner nodes:    6
Number of terminal nodes: 7

Is there a way I have have more control? Eg, I don't want to print n and err, or want standard deviation instead of err printed.

like image 243
YJZ Avatar asked Sep 11 '25 10:09

YJZ


1 Answers

Not a very elegant answer, but if you just want to get rid of n= and err= you can capture the output and edit it.

CO = capture.output(print(as.party(fit)))
CO2 = sub("\\(.*\\)", "", CO)
cat(paste(CO2, collapse="\n"))

Model formula:
Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species

Fitted party:
[1] root
|   [2] Petal.Length < 4.25
|   |   [3] Petal.Length < 3.4
|   |   |   [4] Sepal.Width < 3.25: 4.735 
|   |   |   [5] Sepal.Width >= 3.25: 5.170 
|   |   [6] Petal.Length >= 3.4: 5.640 
|   [7] Petal.Length >= 4.25

I am not sure what standard deviation you want to insert, but I expect you could edit that in the same way.

like image 89
G5W Avatar answered Sep 14 '25 02:09

G5W