r - Depth of a node in partykit -
i building tree using partykit
r package, , wondering if there simple, efficient way determine depth number @ each internal node. example, root node have depth 0, first 2 kid nodes have depth 1, next kid nodes have depth 2, , forth. used calculate minimal depth of variable. below basic example (taken vignette("constparty", package="partykit")
):
library("partykit") library("rpart") data("titanic", package = "datasets") ttnc<-as.data.frame(titanic) ttnc <- ttnc[rep(1:nrow(ttnc), ttnc$freq), 1:4] names(ttnc)[2] <- "gender" rp <- rpart(survived ~ ., data = ttnc) ttnctree<-as.party(rp) plot(ttnctree) #this 1 of many attempts not work internalnodes<-nodeids(ttnctree)[-nodeids(ttnctree, terminal = true)] depth(ttnctree)-unlist(nodeapply(ttnctree, ids=internalnodes, fun=function(n){depth(n)}))
in example, want output similar to:
nodeid = 1 2 4 7 depth = 0 1 2 1
i apologize if question specific.
here's possible solution should efficient enough trees have no more several dozens of nodes. i'm ignoring node #1, 0 hence no point neither calculating or showing (imo)
inters <- nodeids(ttnctree)[-nodeids(ttnctree, terminal = true)][-1] table(unlist(sapply(inters, function(x) intersect(inters, nodeids(ttnctree, = x))))) # 2 4 7 # 1 2 1
Comments
Post a Comment