在rpart.plot中设置拆分标签的格式
我正在用在rpart.plot中设置拆分标签的格式,r,rpart,R,Rpart,我正在用rpart.plot::prp()绘制一棵树,很像: library("rpart.plot") data("ptitanic") data <- ptitanic data$sibsp <- as.integer(data$sibsp) # just to show that these are integers data$age <- as.integer(data$age) # just to show that these are integers tree &
rpart.plot::prp()
绘制一棵树,很像:
library("rpart.plot")
data("ptitanic")
data <- ptitanic
data$sibsp <- as.integer(data$sibsp) # just to show that these are integers
data$age <- as.integer(data$age) # just to show that these are integers
tree <- rpart(survived~., data=data, cp=.02)
prp(tree, , fallen.leaves = FALSE, type=4, extra=1, varlen=0, faclen=0, yesno.yshift=-1)
库(“rpart.plot”)
数据(“ptitanic”)
数据1)有序因子我认为年龄
可以作为一个连续变量,但要处理sibsp
和parch
使其成为有序因子:
data <- transform(data, sibsp = ordered(sibsp), parch = ordered(parch))
tree <- rpart(survived~., data=data, cp=.02)
prp(tree, , fallen.leaves = FALSE, type=4, extra=1, varlen=0, faclen=0, yesno.yshift=-1)
这使得:
(2a)第(2)项的一个变化提供了更多的控制,即可以精确地指定要修改的变量,如下所示:
# next 4 lines are same as in question
data <- ptitanic
data$sibsp <- as.integer(data$sibsp) # just to show that these are integers
data$age <- as.integer(data$age) # just to show that these are integers
tree <- rpart(survived~., data=data, cp=.02)
split.labs2 <- function(x, labs, digits, varlen, faclen) {
sapply(labs, function(lab)
if (grepl("age|sibsp|parch", lab)) {
rhs <- sub(".* ", "", lab);
lab <- sub(rhs, ceiling(as.numeric(rhs)), lab)
} else lab)
}
# similar to (2) except we use clip.right.labs = FALSE and split.labs2
prp(tree, type = 4, fallen.leaves = FALSE, extra=1, varlen=0, faclen=0,
yesno.yshift=-1, clip.right.labs = FALSE, split.fun = split.labs2)
#接下来的4行与所讨论的相同
数据包的3.0.0版(2018年7月)专门使用整数值处理预测值,以自动获得您想要的结果
因此rpart.plot
现在自动打印sibsp>=3
,而不是sibsp>=2.5
,因为它可以看到在训练数据中sibsp
的所有值都是整数
第4.1节有一个例子。谢谢您的回答。使用有序因子确实会迫使分区离散化,但我不确定它是否会提高标签的可读性。在这两种情况下都需要心理调整(“好的,这意味着三个或更多,这意味着两个或更少”),而仅仅=3
和<3
似乎简单得多。此外,年龄(几乎)在基础数据集中总是一个整数(参见data(“ptitanic”)<代码> >我担心代码< > Adv>=9.5 所传达的错误的精确感。事实上,在数据集中有9和10岁的人,但没有一个。谢谢,这是我想象中的ReGEX方法。一个要考虑的问题——如果分裂是代码> x 9.5 < /代码>,那么应用<代码> CELIGN()
到分割点会将x==10
的观测值从右分支移到左分支。请注意,只有eq
、lt
和ge
参数到prp
。没有le
参数和gt
参数,因此您的评论中似乎讨论了这种情况无法发生。好的,因此天花()
应该可以。感谢您的帮助。来自?prp
:3.0.0版中的新版本。如果roundint=TRUE
(默认值)训练数据中预测值的所有值都是整数,然后将该预测值的拆分四舍五入为整数。例如,显示nsiblings<3
,而不是nsiblings<2.5
。这正是我想要的更改。谢谢。
# next 4 lines are same as in question
data <- ptitanic
data$sibsp <- as.integer(data$sibsp) # just to show that these are integers
data$age <- as.integer(data$age) # just to show that these are integers
tree <- rpart(survived~., data=data, cp=.02)
split.labs2 <- function(x, labs, digits, varlen, faclen) {
sapply(labs, function(lab)
if (grepl("age|sibsp|parch", lab)) {
rhs <- sub(".* ", "", lab);
lab <- sub(rhs, ceiling(as.numeric(rhs)), lab)
} else lab)
}
# similar to (2) except we use clip.right.labs = FALSE and split.labs2
prp(tree, type = 4, fallen.leaves = FALSE, extra=1, varlen=0, faclen=0,
yesno.yshift=-1, clip.right.labs = FALSE, split.fun = split.labs2)