rpart树中的错误标签

3

在使用R中的rpart时,我遇到了一些标签问题。

这是我的情况。

我正在处理一个包含分类变量的数据集,以下是数据的摘录。

head(Dataset)
Entity  IL  CP  TD  Budget 
  2      1   3   2     250
  5      2   2   1     663
  6      1   2   3     526 
  2      3   1   2     522

当我绘制决策树并添加标签时,使用的是:
plot(tree) 
text(tree)

我收到了错误的标签:对于实体,我得到了“abcd”。

为什么会出现这种情况,我该如何解决?

感谢您的帮助。

1个回答

5
默认情况下,plot.rpart 只会使用字母标记因子变量的级别,第一个级别将是 a,第二个是 b,以此类推。例如:
library(rpart)
library(ggplot2) #for the data

data("diamonds")    
df <- diamonds[1:2000,]

fit <- rpart(price ~ color + cut + clarity, data = df)
plot(fit)
text(fit)

enter image description here

我认为,与其自定义此图,不如使用专门的rpart绘图包:

library(rpart.plot)
prp(fit)

enter image description here

它有许多自定义选项(例如):

prp(fit,
    type = 4,
    extra = 101,
    fallen.leaves = T,
    box.palette = colorRampPalette(c("red", "white", "green3"))(10),
    round = 2,
    branch.lty = 2,
    branch.lwd = 1,
    space = -1,
    varlen = 0,
    faclen = 0)

enter image description here

另一个选项是:
library(rattle)
fancyRpartPlot(fit,
               type = 4)

enter image description here

这个使用 prp 的内部默认值不同。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接