r - 用文本很好地打印决策树/使用自定义控件 [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
有没有办法让我有更多的控制权?例如,我不想打印n
and err
,或者想要标准偏差而不是err
打印。
解决方案
不是一个非常优雅的答案,但如果您只想摆脱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
我不确定您要插入什么标准偏差,但我希望您可以以相同的方式对其进行编辑。
推荐阅读
- mysql - 如何计算mysql子查询中的重复行
- reactjs - 使用 count 的 i18next 复数返回一个对象而不是字符串
- angular - Angular - 偶尔失败的单元测试(路由器)
- spring - 带有 CosmosDB 的 Spring Data REST - 我可以从响应中排除儿童吗?
- javascript - HTML5 Geolocation 未在 Safari 浏览器上提示位置
- javascript - 书签以查看隐藏的选择
- linux - 在当前目录中的所有目录和子目录中搜索与文件扩展名列表匹配的文件。将这些文件复制到维护文件结构的新目录
- java - 来自 Azure 函数和应用服务的输出 JSON 数组被拆分为单独的消息
- azure-devops - 如何获取 Azure DevOps Pipelines 任务的任务版本?
- driver - 中断处理程序未在为其安装的中断上执行