# function to apply ID to nodes in a dendrogram

I would like to know if there is a function that applies an identifier to all nodes in a given dendrogram (binary tree).

So I want a function that after it on a given tree would do the following:

```attr(tr,"ID")             ## should give 1   or  1

attr(tr[[1]],"ID")        ## should give 2  or 10

attr(tr[[2]],"ID")        ## should give 3  or 11

attr(tr[[c(1,1)]],"ID")   ##  should give 4  or 100
```

etc...

it's 1st child ID should be 1100 it's 2nd child ID should be 1101

Note: - dendrapply() applies a function to all nodes in a tree

Package using= "stats"

``` D=rbind(
+ c(1,1,1,1,1),
+ c(1,2,1,1,1),
+ c(2,2,2,2,2),
+ c(2,2,2,2,1),
+ c(3,3,3,3,3),
+ c(3,3,3,3,2))

Ddend=as.dendrogram(hclust.vector(D))

funID<-function(tr,StartID){
.....
attr(n,"ID")= ID  # for all the nodes in tr
}
```

What would funID be?

This is code taken from stats:::reorder.dendrogram and modified to suit the purpose of labeling the root and each leaf with an increasing integer. It might not exactly fit your specs but see if it does ...

```label.leaves <-
function (x, wts)
{ N=1
if (!inherits(x, "dendrogram"))
stop("we require a dendrogram")
oV <- function(x, wts) {
if (is.leaf(x)) {
attr(x, "ID") <- N; N <<- N+1
return(x)
}
k <- length(x)
if (k == 0L)
stop("invalid (length 0) node in dendrogram")
vals <- numeric(k)
for (j in 1L:k) { N <- N+1
b <- oV(x[[j]], wts)
x[[j]] <- b
vals[j] <- N; N <- N+1
}
x
}
stats:::midcache.dendrogram(oV(x, wts))
}
```

Testing:

```> Ddend.L <- label.leaves(Ddend)
> rapply(Ddend.L, function(x) return( attr(x, "ID") ))
[1] 1 2 3 4 5 6
```