【问题标题】:Obtaining full path from leaf to root for each terminal node with ctree from partykit使用partykit中的ctree为每个终端节点获取从叶子到根的完整路径
【发布时间】:2020-12-10 04:23:25
【问题描述】:

我目前正在使用 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

Plotting the tree

这基本上是我需要的:

[[1]]
[1] 2 1

[[2]]
[1] 5 4 3 1

[[3]]
[1] 6 4 3 1

[[4]]
[1] 7 3 1

如果有任何帮助,我将不胜感激! 谢谢!

【问题讨论】:

    标签: r party ctree


    【解决方案1】:

    下面的函数应该可以解决问题。第一行提取每个节点的孩子列表,从中您可以递归地遍历所有节点。

    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)
    }
    

    这可以应用于任何party 对象:

    get_path(ct)
    ## [[1]]
    ## [1] 2 1
    ## 
    ## [[2]]
    ## [1] 5 4 3 1
    ## 
    ## [[3]]
    ## [1] 6 4 3 1
    ## 
    ## [[4]]
    ## [1] 7 3 1
    

    【讨论】:

    • 非常感谢,正是我需要的。
    猜你喜欢
    • 1970-01-01
    • 2015-08-19
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    相关资源
    最近更新 更多