dendrapply               package:stats               R Documentation

_A_p_p_l_y _a _F_u_n_c_t_i_o_n _t_o _A_l_l _N_o_d_e_s _o_f _a _D_e_n_d_r_o_g_r_a_m

_D_e_s_c_r_i_p_t_i_o_n:

     Apply function 'FUN' to each node of a 'dendrogram' recursively. 
     When  'y <- dendrapply(x, fn)', then 'y' is a dendrogram of the
     same graph structure as 'x' and each for each node, 'y.node[j] <-
     FUN( x.node[j], ...)' (where 'y.node[j]' is an (invalid!) notation
     for the j-th node of y.

_U_s_a_g_e:

     dendrapply(X, FUN, ...)

_A_r_g_u_m_e_n_t_s:

       X: an object of class '"dendrogram"'.

     FUN: an R function to be applied to each dendrogram node,
          typically working on its 'attributes' alone, returning an
          altered version of the same node.

     ...: potential further arguments passed to 'FUN'.

_V_a_l_u_e:

     Usually a dendrogram of the same (graph) structure as 'X'. For
     that, the function must be conceptually of the form 'FUN <-
     function(X) { attributes(X) <- .....;  X }', i.e. returning the
     node with some attributes added or changed.

_N_o_t_e:

     this is still somewhat experimental, and suggestions for
     enhancements (or nice examples of usage) are very welcome.

_A_u_t_h_o_r(_s):

     Martin Maechler

_S_e_e _A_l_s_o:

     'as.dendrogram', 'lapply' for applying a function to each
     component of a  'list'.

_E_x_a_m_p_l_e_s:

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

     ## too simple:
     dendrapply(dhc21, function(n) 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)

