首页 > 解决方案 > 用文本很好地打印决策树/使用自定义控件 [r]

问题描述

我想很好地用文本打印决策树。例如,我可以打印树对象本身:

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

产量

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打印得更整洁:

library(partykit)

as.party(fit)

产量

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

有没有办法让我有更多的控制权?例如,我不想打印nand err,或者想要标准偏差而不是err打印。

标签: rdecision-treerpartparty

解决方案


不是一个非常优雅的答案,但如果您只想摆脱n=并且err=可以捕获输出并对其进行编辑。

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

我不确定您要插入什么标准偏差,但我希望您可以以相同的方式对其进行编辑。


推荐阅读