r - 使用partykit中的ctree为每个终端节点获取从叶子到根的完整路径
问题描述
我目前正在使用 R 包“partykit”中的 ctree,我想知道是否有办法获得从终端节点到根的完整路径。我希望每个叶子都有到根的完整路径,表示为包含节点 ID 的向量。
library(partykit)
ct <- ctree(Species ~ ., data = iris)
Model formula:
Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
Fitted party:
[1] root
| [2] Petal.Length <= 1.9: setosa (n = 50, err = 0.0%)
| [3] Petal.Length > 1.9
| | [4] Petal.Width <= 1.7
| | | [5] Petal.Length <= 4.8: versicolor (n = 46, err = 2.2%)
| | | [6] Petal.Length > 4.8: versicolor (n = 8, err = 50.0%)
| | [7] Petal.Width > 1.7: virginica (n = 46, err = 2.2%)
Number of inner nodes: 3
Number of terminal nodes: 4
这基本上是我需要的:
[[1]]
[1] 2 1
[[2]]
[1] 5 4 3 1
[[3]]
[1] 6 4 3 1
[[4]]
[1] 7 3 1
我将不胜感激任何帮助!谢谢!
解决方案
The following function should do the trick. The first line extracts a list of kids per node and from this you can recursively go through all nodes.
get_path <- function(object) {
## list of kids per node (NULL if terminal)
kids <- lapply(as.list(object$node), "[[", "kids")
## recursively add node IDs of children
add_ids <- function(x) {
ki <- kids[[x[1L]]]
if(is.null(ki)) {
return(list(x))
} else {
x <- lapply(ki, "c", x)
return(do.call("c", lapply(x, add_ids)))
}
}
add_ids(1L)
}
This can then be applied to any party
object:
get_path(ct)
## [[1]]
## [1] 2 1
##
## [[2]]
## [1] 5 4 3 1
##
## [[3]]
## [1] 6 4 3 1
##
## [[4]]
## [1] 7 3 1
推荐阅读
- ruby-on-rails - 如何在 AWS CodeBuild 上运行 docker-compose?
- python - Scrapy on Linkedin 已爬取 0 页
- javascript - Office.context.mailbox.displayNewMessageForm 在移动设备中不起作用
- html - 列表元素的以下兄弟姐妹
- java - Spring Boot - JSON 对象数组到 Java 数组
- sql-server - 必须声明标量变量“@EmailID”
- sql - SSRS 从去年 1 月提取数据
- r - 在R语言中,如果rhandsontable的行名很长,会在屏幕上只显示一部分
- wordpress - 在没有 Ciomand Line 访问和提供商支持的情况下在 Wordpress 上安装 SSL
- python - 如何在三个维度上比较 3D 矢量与平面的方向