\HeaderA{dendrapply}{Apply a Function to All Nodes of a Dendrogram}{dendrapply}
\keyword{iteration}{dendrapply}
\begin{Description}\relax
Apply function \code{FUN} to each node of a \code{\LinkA{dendrogram}{dendrogram}}
recursively.  When  \code{y <- dendrapply(x, fn)}, then \code{y} is a
dendrogram of the same graph structure as \code{x} and for each node,
\code{y.node[j] <- FUN( x.node[j], ...)} (where \code{y.node[j]} is an
(invalid!) notation for the j-th node of y.
\end{Description}
\begin{Usage}
\begin{verbatim}
dendrapply(X, FUN, ...)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{X}] an object of class \code{"\LinkA{dendrogram}{dendrogram}"}.
\item[\code{FUN}] an \R{} function to be applied to each dendrogram node,
typically working on its \code{\LinkA{attributes}{attributes}} alone, returning an
altered version of the same node.
\item[\code{...}] potential further arguments passed to \code{FUN}.
\end{ldescription}
\end{Arguments}
\begin{Value}
Usually a dendrogram of the same (graph) structure as \code{X}.
For that, the function must be conceptually of the form
\code{FUN <- function(X) \{ attributes(X) <- .....;  X \}},
i.e. returning the node with some attributes added or changed.
\end{Value}
\begin{Note}\relax
this is still somewhat experimental, and suggestions for
enhancements (or nice examples of usage) are very welcome.
\end{Note}
\begin{Author}\relax
Martin Maechler
\end{Author}
\begin{SeeAlso}\relax
\code{\LinkA{as.dendrogram}{as.dendrogram}}, \code{\LinkA{lapply}{lapply}} for applying
a function to each component of a \code{list}, \code{\LinkA{rapply}{rapply}}
for doing so to each non-list component of a nested list.
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
require(graphics)

## a smallish simple dendrogram
dhc <- as.dendrogram(hc <- hclust(dist(USArrests), "ave"))
(dhc21 <- dhc[[2]][[1]])

## too simple:
dendrapply(dhc21, function(n) utils::str(attributes(n)))

## toy example to set colored leaf labels :
local({
  colLab <<- function(n) {
      if(is.leaf(n)) {
        a <- attributes(n)
        i <<- i+1
        attr(n, "nodePar") <-
            c(a$nodePar, list(lab.col = mycols[i], lab.font= i%%3))
      }
      n
  }
  mycols <- grDevices::rainbow(attr(dhc21,"members"))
  i <- 0
 })
dL <- dendrapply(dhc21, colLab)
op <- par(mfrow=2:1)
 plot(dhc21)
 plot(dL) ## --> colored labels!
par(op)
\end{ExampleCode}
\end{Examples}

