【问题标题】:How to add labels to the terminal nodes of a ctree (package party)?如何为 ctree(打包方)的终端节点添加标签?
【发布时间】:2012-07-12 01:41:26
【问题描述】:

我使用 ctree 创建了一个二叉分类树。我希望每个终端节点都包含与该节点关联的行名。我怎样才能做到这一点?

例如,对于下面的数据集,我希望最左边的节点分别列出所有年龄

      names       age height young   
1     Abner       18   76.1   yes
2     Abraham     19   77.0   yes
3     Abram       20   78.1   yes
4     Abrasha     21   78.2   yes
5     Absalom     22   78.8   yes
6     Abudemio    23   79.7   yes
7     Abundiantus 24   79.9    no
8     Acacio      25   81.1    no
9     Acario      26   81.2    no
10    Accursius   27   81.8    no
11    Ace         28   82.8    no
12    Acelin      29   83.5    no

【问题讨论】:

    标签: r decision-tree party


    【解决方案1】:

    这里是一个 hacky 解决方案。它只需要对 party 包中的绘图函数的原始源代码进行很少的修改。通过阅读源代码,我注意到有一个terminal_panel 正在调用node_barplot,以防结果是一个因素。 (一切都在R/plot.R函数中,如果你安装了源码包的话。)我们可以修改后面的,在默认的条形图中显示自定义标签。

    只需在 R 提示符下发出以下命令:

    fixInNamespace("node_barplot", pos="package:party")
    

    然后,开始添加我们想要的内容:

    1. labels = NULL, gp = NULL 添加到该函数的现有参数列表中。
    2. 在函数体末尾附近,grid.rect(gp = gpar(fill = "transparent"))之后,添加以下几行:

      if (!is.null(labels)) {
        labs <- as.character(labels[ctreeobj@where==node$nodeID])
        len <- length(labs)
        x <- unit(rep(0.5, len), "npc")
        y <- unit(0.5:len/len, "npc")
        for (i in 1:len) 
          grid.text(labs[i], x=x[i], y=y[i], just="center", gp=gp)
      }
      

      这里的关键思想是选择与选中节点(node$nodeID)对应的标签,我们可以从ctree对象的槽where中获取这个信息(这是一个向量,表示在哪个节点每个案例都结束了)。 if 测试只是为了确保我们可以使用最初编写的函数。 gp 参数可用于更改字体大小或颜色。

    现在对该函数的典型调用是:

    plot(cfit, tp_pars=list(labels=dfrm$names))
    

    其中dfrm$names 是来自名为dfrm 的数据框的一列标签。这是您的数据的插图:

    cfit <- ctree(young ~ age, data=a, 
                  controls=ctree_control(minsplit=2, minbucket=2))
    plot(cfit, tp_args=list(labels=a$names, gp=gpar(fontsize=8, col="darkgrey")))
    

    (我还使用iris 数据集的在线示例对此进行了测试。)

    【讨论】:

    • 非常好,正是我想要的。
    猜你喜欢
    • 2015-08-19
    • 2016-02-09
    • 2015-07-12
    • 2017-11-15
    • 2015-09-09
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多