hxd1011 - 1 year ago 264

R Question

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>")`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**