Dear all,
I have been trying the following without avail and would be very grateful for any help. From a dendrogram (recursive list of lists with some structure), I would like to obtain some information of the component lists and of the enclosing list at the same time. In dendrogram-speech I basically would like the label of the leaf and the height of the enclosing branch.
A dendrogram example (from the help file of stats::dendrogram), and some functions showing how it is structured:
hc <- hclust(dist(USArrests), "ave")
dend1 <- as.dendrogram(hc)
plot(dend1)
str(dend1)
Similarly to dendrapply(), I tried o recursively obtain from the tree a list including, for each member (leaf) the height of the list containing it. However, I fail to fully grasp how the 'recursiveness' is made within the function saving both elements at the leaf and branch levels. For reference the dendrapply function is as follows:
function (X, FUN, ...)
{
FUN <- match.fun(FUN)
if (!inherits(X, "dendrogram"))
stop("'X' is not a dendrogram")
Napply <- function(d) {
r <- FUN(d, ...)
if (!is.leaf(d)) {
if (!is.list(r))
r <- as.list(r)
if (length(r) < (n <- length(d)))
r[seq_len(n)] <- vector("list", n)
r[] <- lapply(d, Napply)
}
r
}
Napply(X)
}
I essentially don't manage to 'save' the height of a branch (a list of lists) so that it can be used at the next iterations for adding to the leafs there. Many thanks for any guidance on how to recursively implement a function.
Kind regards,
Ivan
[[alternative HTML version deleted]]