Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the depth of the tree in RPART model?

Tags:

r

tree

rpart

Suppose I build a toy tree model with RPART, how can I get the depth of the tree?

library(rpart)
library(partykit)
fit=rpart(factor(am)~.,mtcars,control=rpart.control(cp=0,minsplit = 1))
plot(as.party(fit))

I know how to count the leaves, for binary tree, we can approximate the depth by number of leaves, but it is not directly the depth of the tree.

sum(fit$frame$var=="<leaf>")
like image 416
hxd1011 Avatar asked Dec 12 '25 05:12

hxd1011


1 Answers

rpart has a unexported function tree.depth that gives the depth of each node in the vector of node numbers passed to it. Using data from the question:

nodes <- as.numeric(rownames(fit$frame))
max(rpart:::tree.depth(nodes))
## [1] 2
like image 140
G. Grothendieck Avatar answered Dec 13 '25 23:12

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!