# Developers Planet

Peter Calhoun February 2016

### Depth of a node in partykit

I am building a tree using the `partykit` R package, and I am wondering if there is a simple, efficient way to determine the depth number at each internal node. For example, the root node would have depth 0, the first two kid nodes have depth 1, the next kid nodes have depth 2, and so forth. This will eventually be used to calculate the minimal depth of a variable. Below is a very basic example (taken from `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 is one of my many attempts which does NOT work
internalNodes<-nodeids(ttncTree)[-nodeids(ttncTree, terminal = TRUE)]
depth(ttncTree)-unlist(nodeapply(ttncTree, ids=internalNodes, FUN=function(n){depth(n)}))
``````

In this example, I want to output something similar to:

``````nodeid = 1 2 4 7
depth  = 0 1 2 1
``````

I apologize if my question is too specific.

David Arenburg February 2016

Here's a possible solution which should be efficient enough as usually the trees have no more than several dozens of nodes. I'm ignoring node #1, as it is always 0 an hence no point neither calculating it or showing it (IMO)

``````Inters <- nodeids(ttncTree)[-nodeids(ttncTree, terminal = TRUE)][-1]
table(unlist(sapply(Inters, function(x) intersect(Inters, nodeids(ttncTree, from = x)))))
# 2 4 7
# 1 2 1
``````