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 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', 'rapply' for doing so to each non-list
     component of a nested list.

_E_x_a_m_p_l_e_s:

     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)

