Debian Codegraph @

R/depth.R

raw
1
2
3 # devtools::install_github('metrumresearchgroup/sinew')
4 # sinew::makeOxygen(min_depth)
5
6
7 #' @title Find minimum/maximum depth of a dendrogram
8 #' @rdname depth
9 #' @export
10 #' @description
11 #' As the name implies. This can also work for non-dendrogram nested lists.
12 #' @param dend Any nested list object (including \link{dendrogram}).
13 #' @param ... unused at the moment.
14 #' @return Integer, the (min/max) number of nodes from the root to the leafs
15 #' @examples
16 #'
17 #' hc <- hclust(dist(USArrests), "ave")
18 #' (dend1 <- as.dendrogram(hc)) # "print()" method
19 #' is.list(dend1)
20 #' is.list(dend1[[1]][[1]][[1]])
21 #' dend1[[1]][[1]][[1]]
22 #' plot(dend1)
23 #' min_depth(dend1)
24 #' max_depth(dend1)
25 min_depth <- function(dend, ...) {
26 if (!is.list(dend)) {
27 return(1L)
28 } # we reached a leaf, and should just return 1 node
29 # if it is a list, then we may have children, let's check how many we have:
30 n_children <- length(dend)
31 if (n_children < 2) stop("something is odd. Each non-leaf node should have at least two children")
32
33 children_depth <- numeric(n_children)
34 for (i in 1:n_children) {
35 # children_depth[i] <- min_depth(dend[[i]])
36 children_depth[i] <- Recall(dend[[i]])
37 }
38
39 # return 1 for current node
40 1L + min(children_depth)
41 }
42
43
44 #' @rdname depth
45 #' @export
46 max_depth <- function(dend, ...) {
47 if (!is.list(dend)) {
48 return(1L)
49 } # we reached a leaf, and should just return 1 node
50 # if it is a list, then we may have children, let's check how many we have:
51 n_children <- length(dend)
52 if (n_children < 2) stop("something is odd. Each non-leaf node should have at least two children")
53
54 children_depth <- numeric(n_children)
55 for (i in 1:n_children) {
56 children_depth[i] <- Recall(dend[[i]])
57 }
58
59 # return 1 for current node
60 1L + max(children_depth)
61 }