我已绘制了一棵树,理想情况下,我希望该树显示变量的所有标签。例如,显示“花费的时间”(我对变量的标签)而不是“ time_reading”(变量)。特别是到目前为止,我使用的是rpart.plot包:
tree1 <- ...
rpart.plot(tree1)
并且所有节点都显示变量名称,而不是标签。如何添加标签命令以用标签替换变量名?预先感谢您的帮助!
在绘图树中获取所需变量名称的一种方法是更改变量树中的变量名称。原始数据。例如:
data(ptitanic)
mytitanic <- ptitanic
colnames(mytitanic) <- c("passenger class", "survived", "sex",
"age in years", "number siblings or spouses",
"number parents or children")
tree1 <- rpart(survived~., data=mytitanic)
rpart.plot(tree1)
另一种方法是使用split.fun
参数。有关详细信息,请参见vignette
for the rpart.plot package第6.1节。例如:
data(ptitanic)
tree2 <- rpart(survived~., data=ptitanic)
split.fun <- function(x, labs, digits, varlen, faclen)
{
# replace variable names in the labels
labs <- sub("pclass", "passenger class", labs)
# labs <- sub("survived", "survived", labs)
# labs <- sub("sex", "sex", labs)
labs <- sub("age", "age in years", labs)
labs <- sub("sibsp", "number siblings or spouses", labs)
labs <- sub("parch", "number parents or children", labs)
labs # return the modified labels
}
rpart.plot(tree2, split.fun=split.fun)