rpart创建一个表,该表指示观察是否属于节点
下图显示了我要执行的操作:rpart创建一个表,该表指示观察是否属于节点,r,rpart,R,Rpart,下图显示了我要执行的操作: 使用rpart为某些数据集生长树 创建一个表,其中原始数据集中每个观测值一行,树中每个节点一列,外加一个id。如果观测值属于该节点,则节点列的值应为1,否则为零 这是我写的一些代码: 库(rpart) 图书馆(嘎嘎声) 资料 有没有一个包裹可以满足我的需要 好的,没有,但是这项工作在rpart4.1.13版中进行 函数获取给定叶索引的二进制矩阵OP 获取节点 # function that gives us the leaf index get_where <
rpart
为某些数据集生长树库(rpart)
图书馆(嘎嘎声)
资料
有没有一个包裹可以满足我的需要
好的,没有,但是这项工作在rpart
4.1.13版中进行
函数获取给定叶索引的二进制矩阵OP
获取节点
# function that gives us the leaf index
get_where <- function(object, newdata, na.action = na.pass){
if (is.null(attr(newdata, "terms"))) {
Terms <- delete.response(object$terms)
newdata <- model.frame(Terms, newdata, na.action = na.action,
xlev = attr(object, "xlevels"))
if (!is.null(cl <- attr(Terms, "dataClasses")))
.checkMFClasses(cl, newdata, TRUE)
}
pred.rpart(object, rpart.matrix(newdata))
}
environment(get_where) <- environment(rpart)
# check that we get the correct value
where <- get_where(fit, data)
stopifnot(isTRUE(all.equal(
fit$frame$yval[where], unname(predict(fit, newdata = data)))))
# function to get the binary matrix OP wants given the leaf index
get_nodes <- function(object, where){
rn <- row.names(object$frame)
edges <- descendants(as.numeric(rn))
o <- t(edges)[where, , drop = FALSE]
colnames(o) <- paste0("GP", rn)
o
}
environment(get_nodes) <- environment(rpart)
# use function
nodes <- get_nodes(fit, where)
head(nodes, 9)
#R GP1 GP2 GP3 GP6 GP7 GP14 GP15
#R [1,] TRUE FALSE TRUE FALSE TRUE TRUE FALSE
#R [2,] TRUE FALSE TRUE FALSE TRUE FALSE TRUE
#R [3,] TRUE FALSE TRUE FALSE TRUE TRUE FALSE
#R [4,] TRUE TRUE FALSE FALSE FALSE FALSE FALSE
#R [5,] TRUE FALSE TRUE FALSE TRUE FALSE TRUE
#R [6,] TRUE FALSE TRUE TRUE FALSE FALSE FALSE
#R [7,] TRUE FALSE TRUE TRUE FALSE FALSE FALSE
#R [8,] TRUE FALSE TRUE TRUE FALSE FALSE FALSE
#R [9,] TRUE FALSE TRUE TRUE FALSE FALSE FALSE
# compare with
head(data, 9)
#R Kyphosis Age Number Start
#R 1 absent 71 3 5
#R 2 absent 158 3 14
#R 3 present 128 4 5
#R 4 absent 2 5 1
#R 5 absent 1 4 15
#R 6 absent 1 2 16
#R 7 absent 61 2 17
#R 8 absent 37 3 16
#R 9 absent 113 2 16