Debian Codegraph @

R/cutree.dendrogram.R

raw
1 # Copyright (C) Tal Galili
2 #
3 # This file is part of dendextend.
4 #
5 # dendextend is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # dendextend is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # A copy of the GNU General Public License is available at
16 # http://www.r-project.org/Licenses/
17 #
18
19
20 #' @title Sort the values level in a vector
21 #' @export
22 #' @description
23 #' Takes a numeric vector and sort its values so that they
24 #' would be increasing from left to right.
25 #' It is different from \code{\link{sort}} in that the function
26 #' will only "sort" the values levels, and not the vector itself.
27 #'
28 #' This function is useful for \link[dendextend]{cutree} - making the
29 #' sort_cluster_numbers parameter possible. Using that parameter with TRUE
30 #' makes the clusters id's from cutree to be ordered from left to right.
31 #' e.g: the left most cluster in the tree will be numbered "1", the one
32 #' after it will be "2" etc...).
33 #'
34 #' @param x a numeric vector.
35 #' @param MARGIN passed to \link{apply}. It is a vector giving the subscripts
36 #' which the function will be applied over.
37 #' E.g., for a matrix 1 indicates rows, 2 indicates columns,
38 #' c(1, 2) indicates rows and columns. Where X has named dimnames,
39 #' it can be a character vector selecting dimension names.
40 #' @param decreasing logical (FALSE). Should the sort be increasing or decreasing?
41 #' @param force_integer logical (FALSE). Should the values returned be integers?
42 #' @param warn logical (default from dendextend_options("warn") is FALSE).
43 #' Set if warning are to be issued, it is safer to keep this at TRUE,
44 #' but for keeping the noise down, the default is FALSE.
45 #' (for example when x had NA values in it)
46 #' @param ... ignored.
47 #' @return if x is an object - it returns logical - is the object of class dendrogram.
48 #' @seealso \code{\link{sort}}, \code{\link{fac2num}}, \code{\link[dendextend]{cutree}}
49 #' @examples
50 #'
51 #' x <- 1:4
52 #' sort_levels_values(x) # 1 2 3 4
53 #'
54 #' x <- c(4:1)
55 #' names(x) <- letters[x]
56 #' attr(x, "keep_me") <- "a cat"
57 #' sort_levels_values(x) # 1 2 3 4
58 #'
59 #' x <- c(4:1, 4, 2)
60 #' sort_levels_values(x) # 1 2 3 4 1 3
61 #'
62 #' x <- c(2, 2, 3, 2, 1)
63 #' sort_levels_values(x) # 1 1 2 1 3
64 #'
65 #' x <- matrix(16:1, 4, 4)
66 #' rownames(x) <- letters[1:4]
67 #' x
68 #' apply(x, 2, sort_levels_values)
69 sort_levels_values <- function(x, MARGIN = 2, decreasing = FALSE, force_integer = FALSE, warn = dendextend_options("warn"), ...) {
70 if (any(is.na(x))) {
71 if (warn) warning("'x' had NA values - it is returned as is.")
72 return(x)
73 }
74
75 if (!is.numeric(x)) stop("x must be a numeric vector/matrix")
76
77 # make a function that would work on a vector
78 sort_levels_values_vec <- function(x) {
79 f_x <- factor(x, levels = unique(x))
80 levels(f_x) <- sort(as.numeric(levels(f_x)), decreasing = decreasing)
81 new_x <- x
82 # force_integer is available in the wrapping function
83 new_x[seq_along(new_x)] <- fac2num(f_x, force_integer = force_integer) # this makes sure we retain things like names and attr
84 return(new_x)
85 }
86
87 if (is.matrix(x)) {
88 new_x <- apply(x, MARGIN = MARGIN, sort_levels_values_vec)
89 } else {
90 new_x <- sort_levels_values_vec(x)
91 }
92
93 return(new_x)
94 }
95
96
97
98
99
100 #' @title Check if numbers are natural
101 #' @export
102 #' @description Vectorized function for checking if numbers are natural or not.
103 #' Helps in checking if a vector is of type "order".
104 #' @param x a vector of numbers
105 #' @param tol tolerence to floating point issues.
106 #' @param ... (not currently in use)
107 #' @return logical - is the entered number natural or not.
108 #' @author Marco Gallotta (a.k.a: marcog), Tal Galili
109 #' @source
110 #' This function was written by marcog, as an answer to my question here:
111 #' \url{https://stackoverflow.com/questions/4562257/what-is-the-fastest-way-to-check-if-a-number-is-a-positive-natural-number-in-r}
112 #' @seealso \code{\link{is.numeric}}, \code{\link{is.double}}, \code{\link{is.integer}}
113 #' @examples
114 #' is.natural.number(1) # is TRUE
115 #' (x <- seq(-1, 5, by = 0.5))
116 #' is.natural.number(x)
117 #' # is.natural.number( "a" )
118 #' all(is.natural.number(x))
119 is.natural.number <- function(x, tol = .Machine$double.eps^0.5, ...) {
120 x > tol & abs(x - round(x)) < tol
121 }
122
123 ## Not important enough to include
124 # all.natural.numbers <- function(x) all(is.natural.number(x)) # check if all the numbers in a vector are natural
125 # why is this important?
126 # because it can enable one to check if what we have is a vector of "order"
127
128
129
130
131
132
133 #' @title cutree for dendrogram (by 1 height only!)
134 #' @export
135 #' @description Cuts a dendrogram tree into several groups
136 #' by specifying the desired cut height (only a single height!).
137 #' @param dend a dendrogram object
138 #' @param h numeric scalar (NOT a vector) with a height where the dend should be cut.
139 #' @param use_labels_not_values logical, defaults to TRUE. If the actual labels of the
140 #' clusters do not matter - and we want to gain speed (say, 10 times faster) -
141 #' then use FALSE (gives the "leaves order" instead of their labels.).
142 #' @param order_clusters_as_data logical, defaults to TRUE. There are two ways by which
143 #' to order the clusters: 1) By the order of the original data. 2) by the order of the
144 #' labels in the dendrogram. In order to be consistent with \link[stats]{cutree}, this is set
145 #' to TRUE.
146 #' @param warn logical (default from dendextend_options("warn") is FALSE).
147 #' Set if warning are to be issued, it is safer to keep this at TRUE,
148 #' but for keeping the noise down, the default is FALSE.
149 #' @param ... (not currently in use)
150 #' @return \code{cutree_1h.dendrogram} returns an integer vector with group memberships
151 #' @author Tal Galili
152 #' @seealso \code{\link{hclust}}, \code{\link{cutree}}
153 #' @examples
154 #' hc <- hclust(dist(USArrests[c(1, 6, 13, 20, 23), ]), "ave")
155 #' dend <- as.dendrogram(hc)
156 #' cutree(hc, h = 50) # on hclust
157 #' cutree_1h.dendrogram(dend, h = 50) # on a dendrogram
158 #'
159 #' labels(dend)
160 #'
161 #' # the default (ordered by original data's order)
162 #' cutree_1h.dendrogram(dend, h = 50, order_clusters_as_data = TRUE)
163 #'
164 #' # A different order of labels - order by their order in the tree
165 #' cutree_1h.dendrogram(dend, h = 50, order_clusters_as_data = FALSE)
166 #'
167 #'
168 #' # make it faster
169 #' \dontrun{
170 #' library(microbenchmark)
171 #' microbenchmark(
172 #' cutree_1h.dendrogram(dend, h = 50),
173 #' cutree_1h.dendrogram(dend, h = 50, use_labels_not_values = FALSE)
174 #' )
175 #' # 0.8 vs 0.6 sec - for 100 runs
176 #' }
177 #'
178 cutree_1h.dendrogram <- function(dend, h,
179 order_clusters_as_data = TRUE, use_labels_not_values = TRUE,
180 warn = dendextend_options("warn"), ...) {
181 if (missing(h)) stop("h is missing")
182
183 if (length(h) > 1) {
184 if (warn) warning("h has length > 1 and only the first element will be used")
185 h <- h[1]
186 }
187
188 # deal with cases that we cut the dend to all leaves. (negative h)
189 if (h < 0) {
190 labels_dend <- labels(dend)
191 cluster_vec <- 1:length(labels_dend)
192 names(cluster_vec)[order.dendrogram(dend)] <- labels_dend
193 return(cluster_vec)
194 }
195
196
197
198 if (use_labels_not_values) {
199 FUN <- labels
200 } else {
201 FUN <- order.dendrogram
202 }
203
204
205 # cut_replace <- function(dend, h, FUN) {
206 # if(attr(dend, "height") <= h ) return(list(FUN(dend)))
207 #
208 # clusters <- list()
209 # counter <- 1
210 #
211 # add_clusters <- function(dend_node)
212 # {
213 # if(is.leaf(dend_node)) {
214 # clusters[[counter]] <<-FUN(dend_node)
215 # return(NULL)
216 # }
217 # for(i in seq(dend_node)) {
218 # dend_node_child_height <- attr(dend_node[[i]], "height")
219 # if(dend_node_child_height>h) { # notice I'm using > and not >= (this might be worth checking further)
220 # if(is.leaf(dend_node[[i]])) {
221 # clusters[[counter]] <<- FUN(dend_node[[i]])
222 # } else {
223 # add_clusters(dend_node[[i]])
224 # }
225 # } else { # this node is now a new cluser, hence:
226 # clusters[[counter]] <<- FUN(dend_node[[i]])
227 # counter <<- 1 + counter
228 # }
229 # }
230 # return(NULL)
231 # }
232 # add_clusters(dend)
233 # return(clusters)
234 # }
235 # an alternatice which is not faster (but may be used in the future for making this into an Rcpp function!)
236 # names_in_clusters <- cut_replace(dend, h, FUN)
237
238 # names_in_clusters <- sapply(cut(dend, h = h)$lower, FUN) # If the proper labels are not important, this function is around 10 times faster than using labels (so it is much better for some other algorithms)
239 names_in_clusters <- cut_lower_fun(dend, h, FUN) # If the proper labels are not important, this function is around 10 times faster than using labels (so it is much better for some other algorithms)
240 # Type of output:
241 # [[1]]
242 # [1] "Minnesota"
243 #
244 # [[2]]
245 # [1] "Maryland" "Colorado" "Alabama" "Illinois"
246
247 number_of_clusters <- length(names_in_clusters)
248 number_of_members_in_clusters <- sapply(names_in_clusters, length) # a list with item per cluster. each item is a character vector with the names of the items in that cluster
249 cluster_vec <- rep(rev(seq_len(number_of_clusters)), times = number_of_members_in_clusters) # like in the original cutree
250 # I am using "rev" on "seq_len" - so that the resulting cluster numbers will be consistant with those of cutree.hclust
251
252 # 2011-01-10: this is to fix the "bug" (I don't think it's a feature) of having the cut.dendrogram return splitted tree when h is heigher then the tree...
253 # now it gives consistent results with cutree
254 if (h > attr(dend, "height")) cluster_vec <- rep(1L, length(cluster_vec))
255
256 names(cluster_vec) <- unlist(names_in_clusters)
257
258
259 # note: The order of the items in cluster_vec, is according to their order in the dendrogram.
260 # If the dendrogram was created through as.dendrogram(hclust_object)
261 # The original order of the names of the items, from which the hclust (and the dendrogram) object was created from, will not be preserved!
262
263 clusters_order <- order.dendrogram(dend)
264
265 if (order_clusters_as_data) {
266 if (!all(clusters_order %in% seq_along(clusters_order))) {
267 if (warn) {
268 warning("rank() was used for the leaves order number! \nExplenation: leaves tip number (the order), and the ranks of these numbers - are not equal.\n The dend was probably subsetted, pruned and/or merged with other dends- and now the order \n labels don't make so much sense (hence, the rank on them was used).")
269 warning("Here is the cluster order vector (from the dend tips) \n", paste(clusters_order, collapse = ", "), "\n")
270 }
271 clusters_order <- rank(clusters_order, ties.method = "first") # we use the "first" ties method - to handle the cases of ties in the ranks (after splits/merges with other dends)
272 }
273
274 cluster_vec <- cluster_vec[order(clusters_order)] # this reorders the cluster_vec according to the original order of the items from which the dend (maybe hclust) was created
275 }
276
277 # 2013-07-28: stay consistant with hclust:
278 # if we have as many clusters as items - they should be numbered
279 # from left to right...
280 dend_size <- nleaves(dend, method = "order")
281 if (number_of_clusters == dend_size) cluster_vec[seq_len(dend_size)] <- seq_len(dend_size)
282
283 return(cluster_vec)
284 }
285
286
287
288
289
290
291
292
293
294
295
296 #' @title Which height will result in which k for a dendrogram
297 #' @description Which height will result in which k for a dendrogram.
298 #' This helps with speeding up the \link{cutree.dendrogram} function.
299 #' @export
300 #' @aliases
301 #' dendextend_heights_per_k.dendrogram
302 #' @param dend a dendrogram.
303 #' @param ... not used.
304 #' @return a vector of heights, with its names being the k clusters that will
305 #' result for cutting the dendrogram at each height.
306 #'
307 #' @examples
308 #' \dontrun{
309 #' hc <- hclust(dist(USArrests[1:4, ]), "ave")
310 #' dend <- as.dendrogram(hc)
311 #' heights_per_k.dendrogram(dend)
312 #' ## 1 2 3 4
313 #' ## 86.47086 68.84745 45.98871 28.36531
314 #'
315 #' cutree(hc, h = 68.8) # and indeed we get 2 clusters
316 #'
317 #' unbranch_dend <- unbranch(dend, 2)
318 #' plot(unbranch_dend)
319 #' heights_per_k.dendrogram(unbranch_dend)
320 #' # 1 3 4
321 #' # 97.90023 57.41808 16.93594
322 #' # we do NOT have a height for k=2 because of the tree's structure.
323 #'
324 #' }
325 heights_per_k.dendrogram <- function(dend, ...) {
326 # gets a dendro tree
327 # returns a vector of heights, and the k clusters we'll get for each of them.
328
329 our_dend_heights <- sort(unique(get_branches_heights(dend, sort = FALSE)), TRUE)
330
331 heights_to_remove_for_A_cut <- min(-diff(our_dend_heights)) / 2 # the height to add so to be sure we get a "clear" cut
332 heights_to_cut_by <- c(
333 (max(our_dend_heights) + heights_to_remove_for_A_cut), # adding the height for 1 clusters only (this is not mandetory and could be different or removed)
334 (our_dend_heights - heights_to_remove_for_A_cut)
335 )
336 # names(heights_to_cut_by) <- sapply(heights_to_cut_by, function(h) {length(cut(dend, h = h)$lower)}) # this is the SLOW line - I need to do it differently...
337 names(heights_to_cut_by) <- sapply(heights_to_cut_by, function(h) {
338 length(cut(dend, h = h)$lower)
339 }) # this is the SLOW line - I need to do it differently...
340
341
342 dend_size <- nleaves(dend)
343 # I use "length(heights_to_cut_by)" for cases when I don't have a height for every possible cut
344 names(heights_to_cut_by)[length(heights_to_cut_by)] <- as.character(dend_size) # should always be the max...
345 names(heights_to_cut_by)[1] <- "1" # should always be 1. (the fact that it's currently not is a bug - remove this line once it is fixed)
346 return(heights_to_cut_by)
347 # notice we might have certion k's that won't exist in this list!
348 }
349
350
351
352
353
354
355 #' @title cutree for dendrogram (by 1 k value only!)
356 #' @export
357 #' @description Cuts a dendrogram tree into several groups
358 #' by specifying the desired number of clusters k (only a single k value!).
359 #'
360 #' In case there exists no such k for which exists a relevant split of the
361 #' dendrogram, a warning is issued to the user, and NA is returned.
362 #' @param dend a dendrogram object
363 #' @param k numeric scalar (not a vector!) with the number of clusters
364 #' the tree should be cut into.
365 #' @param dend_heights_per_k a named vector that resulted from running.
366 #' \code{heights_per_k.dendrogram}. When running the function many times,
367 #' supplying this object will help improve the running time.
368 #' @param use_labels_not_values logical, defaults to TRUE. If the actual labels of the
369 #' clusters do not matter - and we want to gain speed (say, 10 times faster) -
370 #' then use FALSE (gives the "leaves order" instead of their labels.).
371 #' This is passed to \code{cutree_1h.dendrogram}.
372 #' @param order_clusters_as_data logical, defaults to TRUE. There are two ways by which
373 #' to order the clusters: 1) By the order of the original data. 2) by the order of the
374 #' labels in the dendrogram. In order to be consistent with \link[stats]{cutree}, this is set
375 #' to TRUE.
376 #' This is passed to \code{cutree_1h.dendrogram}.
377 #' @param warn logical (default from dendextend_options("warn") is FALSE).
378 #' Set if warning are to be issued, it is safer to keep this at TRUE,
379 #' but for keeping the noise down, the default is FALSE.
380 #' Should the function send a warning in case the desried k is not available?
381 #' @param ... (not currently in use)
382 #' @return \code{cutree_1k.dendrogram} returns an integer vector with group
383 #' memberships.
384 #'
385 #' In case there exists no such k for which exists a relevant split of the
386 #' dendrogram, a warning is issued to the user, and NA is returned.
387 #' @author Tal Galili
388 #' @seealso \code{\link{hclust}}, \code{\link{cutree}},
389 #' \code{\link{cutree_1h.dendrogram}}
390 #' @examples
391 #' hc <- hclust(dist(USArrests[c(1, 6, 13, 20, 23), ]), "ave")
392 #' dend <- as.dendrogram(hc)
393 #' cutree(hc, k = 3) # on hclust
394 #' cutree_1k.dendrogram(dend, k = 3) # on a dendrogram
395 #'
396 #' labels(dend)
397 #'
398 #' # the default (ordered by original data's order)
399 #' cutree_1k.dendrogram(dend, k = 3, order_clusters_as_data = TRUE)
400 #'
401 #' # A different order of labels - order by their order in the tree
402 #' cutree_1k.dendrogram(dend, k = 3, order_clusters_as_data = FALSE)
403 #'
404 #'
405 #' # make it faster
406 #' \dontrun{
407 #' library(microbenchmark)
408 #' dend_ks <- heights_per_k.dendrogram
409 #' microbenchmark(
410 #' cutree_1k.dendrogram = cutree_1k.dendrogram(dend, k = 4),
411 #' cutree_1k.dendrogram_no_labels = cutree_1k.dendrogram(dend,
412 #' k = 4, use_labels_not_values = FALSE
413 #' ),
414 #' cutree_1k.dendrogram_no_labels_per_k = cutree_1k.dendrogram(dend,
415 #' k = 4, use_labels_not_values = FALSE,
416 #' dend_heights_per_k = dend_ks
417 #' )
418 #' )
419 #' # the last one is the fastest...
420 #' }
421 #'
422 cutree_1k.dendrogram <- function(dend, k,
423 dend_heights_per_k = NULL,
424 use_labels_not_values = TRUE,
425 order_clusters_as_data = TRUE,
426 warn = dendextend_options("warn"), ...) {
427 # if(!is.integer(k) && warn) warning("k is not an integer - using k<-as.integer(k)")
428 k <- as.integer(k) # making this consistant with cutree.hclust!!
429
430 # STOPING RULES:
431
432 # if k is not natural - stop!
433 if (!is.natural.number(k)) stop(paste("k must be a natural number! The k you used (", k, ") is not a natural number"))
434
435 # if k is "too large" then stop!
436 if (k > nleaves(dend)) stop(paste("elements of 'k' must be between 1 and", nleaves(dend)))
437
438 # if k is 1 - it is trivial to run and return:
439 if (k == 1L) {
440 h_to_use <- attr(dend, "height") + 1
441 cluster_vec <- cutree_1h.dendrogram(dend,
442 h = h_to_use,
443 use_labels_not_values = use_labels_not_values,
444 order_clusters_as_data = order_clusters_as_data,
445 ...
446 )
447 return(cluster_vec)
448 }
449
450 # deal with cases that we cut the dend to all leaves. (k == nleaves)
451 if (k == nleaves(dend)) {
452 labels_dend <- labels(dend)
453 cluster_vec <- 1:length(labels_dend)
454 names(cluster_vec)[order.dendrogram(dend)] <- labels_dend
455 return(cluster_vec)
456 }
457
458
459
460 # step 1: find all possible h cuts for dend
461 if (is.null(dend_heights_per_k)) {
462 # since this is a step which takes a long time, If possible, I'd rather supply this to the function, so to make sure it runs faster...
463 dend_heights_per_k <- heights_per_k.dendrogram(dend)
464 }
465
466
467 # step 2: Check location in the vector of the height for the k we are interested in
468 height_for_our_k <- which(names(dend_heights_per_k) == k)
469 if (length(height_for_our_k) != 0) # if such a height exists
470 {
471 h_to_use <- dend_heights_per_k[height_for_our_k]
472 cluster_vec <- cutree_1h.dendrogram(dend,
473 h = h_to_use,
474 use_labels_not_values = use_labels_not_values,
475 order_clusters_as_data = order_clusters_as_data,
476 ...
477 )
478 # if(to_print) print(paste("The dendrogram was cut at height",
479 # round(h_to_use, 4), "in order to create",k, "clusters."))
480 } else {
481 cluster_vec <- rep(NA, nleaves(dend, method = "order"))
482
483 # telling the user way he can't use this k
484 if (warn) {
485 warning("Couldn't cut the dend - returning NA.")
486
487 k_s <- as.numeric(names(dend_heights_per_k))
488 # either his k is outside the possible options
489 if (k > max(k_s) || k < min(k_s)) {
490 range_for_clusters <- paste("[", paste(range(k_s), collapse = "-"), "]", sep = "") # it's always supposed to be between 1 to max number of items (so this could be computed in more efficient ways)
491 warning(paste("No cut exists for creating", k, "clusters. The possible range for clusters is:", range_for_clusters))
492 } else {
493 warning(paste("You (probably) have some branches with equal heights so that there exist no height(h) that can create", k, " clusters"))
494 }
495 }
496 }
497 return(cluster_vec)
498 }
499
500
501
502
503
504 #' @title Cut a Tree (Dendrogram/hclust/phylo) into Groups of Data
505 #' @export
506 #' @description Cuts a dendrogram tree into several groups
507 #' by specifying the desired number of clusters k(s), or cut height(s).
508 #'
509 #' For \code{hclust.dendrogram} -
510 #' In case there exists no such k for which exists a relevant split of the
511 #' dendrogram, a warning is issued to the user, and NA is returned.
512 #' @rdname cutree-methods
513 #'
514 #' @param tree a dendrogram object
515 #' @param k numeric scalar (OR a vector) with the number of clusters
516 #' the tree should be cut into.
517 #' @param h numeric scalar (OR a vector) with a height where the tree
518 #' should be cut.
519 #' @param dend_heights_per_k a named vector that resulted from running.
520 #' \code{heights_per_k.dendrogram}. When running the function many times,
521 #' supplying this object will help improve the running time if using k!=NULL .
522 #' @param use_labels_not_values logical, defaults to TRUE. If the actual labels of the
523 #' clusters do not matter - and we want to gain speed (say, 10 times faster) -
524 #' then use FALSE (gives the "leaves order" instead of their labels.).
525 #' This is passed to \code{cutree_1h.dendrogram}.
526 #' @param order_clusters_as_data logical, defaults to TRUE. There are two ways by which
527 #' to order the clusters: 1) By the order of the original data. 2) by the order of the
528 #' labels in the dendrogram. In order to be consistent with \link[stats]{cutree}, this is set
529 #' to TRUE.
530 #' This is passed to \code{cutree_1h.dendrogram}.
531 #' @param warn logical (default from dendextend_options("warn") is FALSE).
532 #' Set if warning are to be issued, it is safer to keep this at TRUE,
533 #' but for keeping the noise down, the default is FALSE.
534 #' Should the function send a warning in case the desried k is not available?
535 #' @param try_cutree_hclust logical. default is TRUE. Since cutree for hclust is
536 #' MUCH faster than for dendrogram - cutree.dendrogram will first try to change the
537 #' dendrogram into an hclust object. If it will fail (for example, with unbranched trees),
538 #' it will continue using the cutree.dendrogram function.
539 #' If try_cutree_hclust=FALSE, it will force to use cutree.dendrogram and not
540 #' cutree.hclust.
541 #' @param NA_to_0L logical. default is TRUE. When no clusters are possible,
542 #' Should the function return 0 (TRUE, default), or NA (when set to FALSE).
543 #' @param ... (not currently in use)
544 #'
545 #' @details
546 #' At least one of k or h must be specified, k overrides h if both are given.
547 #'
548 #' as opposed to \link[stats]{cutree} for hclust, \code{cutree.dendrogram} allows the
549 #' cutting of trees at a given height also for non-ultrametric trees
550 #' (ultrametric tree == a tree with monotone clustering heights).
551 #'
552 #' @return
553 #'
554 #' If k or h are scalar - \code{cutree.dendrogram} returns an integer vector with group
555 #' memberships.
556 #' Otherwise a matrix with group memberships is returned where each column
557 #' corresponds to the elements of k or h, respectively
558 #' (which are also used as column names).
559 #'
560 #' In case there exists no such k for which exists a relevant split of the
561 #' dendrogram, a warning is issued to the user, and NA is returned.
562 #'
563 #'
564 #' @author
565 #' \code{cutree.dendrogram} was written by Tal Galili.
566 #' \code{cutree.hclust} is redirecting the function
567 #' to \link[stats]{cutree} from base R.
568 #'
569 #' @seealso \code{\link{hclust}}, \code{\link[stats]{cutree}},
570 #' \code{\link{cutree_1h.dendrogram}}, \code{\link{cutree_1k.dendrogram}},
571 #'
572 #' @examples
573 #'
574 #' \dontrun{
575 #' hc <- hclust(dist(USArrests[c(1, 6, 13, 20, 23), ]), "ave")
576 #' dend <- as.dendrogram(hc)
577 #' unbranch_dend <- unbranch(dend, 2)
578 #'
579 #' cutree(hc, k = 2:4) # on hclust
580 #' cutree(dend, k = 2:4) # on dendrogram
581 #'
582 #' cutree(hc, k = 2) # on hclust
583 #' cutree(dend, k = 2) # on dendrogram
584 #'
585 #' cutree(dend, h = c(20, 25.5, 50, 170))
586 #' cutree(hc, h = c(20, 25.5, 50, 170))
587 #'
588 #' # the default (ordered by original data's order)
589 #' cutree(dend, k = 2:3, order_clusters_as_data = FALSE)
590 #' labels(dend)
591 #'
592 #' # as.hclust(unbranch_dend) # ERROR - can not do this...
593 #' cutree(unbranch_dend, k = 2) # all NA's
594 #' cutree(unbranch_dend, k = 1:4)
595 #' cutree(unbranch_dend, h = c(20, 25.5, 50, 170))
596 #' cutree(dend, h = c(20, 25.5, 50, 170))
597 #'
598 #'
599 #' library(microbenchmark)
600 #' ## this shows how as.hclust is expensive - but still worth it if possible
601 #' microbenchmark(
602 #' cutree(hc, k = 2:4),
603 #' cutree(as.hclust(dend), k = 2:4),
604 #' cutree(dend, k = 2:4),
605 #' cutree(dend, k = 2:4, try_cutree_hclust = FALSE)
606 #' )
607 #' # the dendrogram is MUCH slower...
608 #'
609 #' # Unit: microseconds
610 #' ## expr min lq median uq max neval
611 #' ## cutree(hc, k = 2:4) 91.270 96.589 99.3885 107.5075 338.758 100
612 #' ## tree(as.hclust(dend),
613 #' ## k = 2:4) 1701.629 1767.700 1854.4895 2029.1875 8736.591 100
614 #' ## cutree(dend, k = 2:4) 1807.456 1869.887 1963.3960 2125.2155 5579.705 100
615 #' ## cutree(dend, k = 2:4,
616 #' ## try_cutree_hclust = FALSE) 8393.914 8570.852 8755.3490 9686.7930 14194.790 100
617 #'
618 #' # and trying to "hclust" is not expensive (which is nice...)
619 #' microbenchmark(
620 #' cutree_unbranch_dend = cutree(unbranch_dend, k = 2:4),
621 #' cutree_unbranch_dend_not_trying_to_hclust =
622 #' cutree(unbranch_dend, k = 2:4, try_cutree_hclust = FALSE)
623 #' )
624 #'
625 #'
626 #' ## Unit: milliseconds
627 #' ## expr min lq median uq max neval
628 #' ## cutree_unbranch_dend 7.309329 7.428314 7.494107 7.752234 17.59581 100
629 #' ## cutree_unbranch_dend_not
630 #' ## _trying_to_hclust 6.945375 7.079198 7.148629 7.577536 16.99780 100
631 #' ## There were 50 or more warnings (use warnings() to see the first 50)
632 #'
633 #' # notice that if cutree can't find clusters for the desired k/h, it will produce 0's instead!
634 #' # (It will produce a warning though...)
635 #' # This is a different behaviout than stats::cutree
636 #' # For example:
637 #' cutree(as.dendrogram(hclust(dist(c(1, 1, 1, 2, 2)))),
638 #' k = 5
639 #' )
640 #' }
641 #'
642 cutree <- function(tree, k = NULL, h = NULL, ...) {
643 UseMethod("cutree")
644 }
645
646
647 #' @export
648 #' @rdname cutree-methods
649 cutree.default <- function(tree, k = NULL, h = NULL, ...) {
650 cutree(as.dendrogram(tree), k = k, h = h, ...)
651 # stop("Function cutree is only available for hclust/dendrogram/phylo objects only.")
652 }
653
654 #' @export
655 #' @rdname cutree-methods
656 cutree.hclust <- function(tree, k = NULL, h = NULL,
657 use_labels_not_values = TRUE, # ignored here...
658 order_clusters_as_data = TRUE,
659 warn = dendextend_options("warn"),
660 NA_to_0L = TRUE, # ignored here...
661 ...) {
662 sort_cluster_numbers <- TRUE
663
664 ## Add an important warning before R crashes.
665 if (warn) {
666 if (any(is.na(labels(tree)))) {
667 warning("'tree' has NA's in its labels (e.g: labels(tree)) -
668 cutree might crash R.
669 If you used as.hclust on a subset of a dendrogram (e.g: dend[[1]]),
670 Make sure to first fix the dendrogram's order tips. See:
671 help('order.dendrogram<-')
672 for suggestion on how to do that.
673
674 (use warn=FALSE if you don't want to see this warning again)
675 ")
676 # ANSWER <- menu(c("Yes (continue)", "No (stop)"), graphics = FALSE, title = "Are you sure you want to proceed with cutree?")
677 # if(exists("ANSWER") && ANSWER==2) stop("'cutree' was stopped by the user.")
678 }
679 }
680
681
682 clusters <- stats::cutree(tree, k = k, h = h, ...)
683 if (!order_clusters_as_data) {
684 if (is.matrix(clusters)) {
685 clusters <- clusters[tree$order, ]
686 } else {
687 clusters <- clusters[tree$order]
688 }
689 }
690
691
692 # sort the clusters id
693 if (sort_cluster_numbers) clusters <- sort_levels_values(clusters, force_integer = TRUE, warn = FALSE)
694 # we know that cluster id is an integer, so it is fine to use force_integer = TRUE
695
696 return(clusters)
697 }
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712 # ' @S3method cutree phylo
713 #' @export
714 #' @rdname cutree-methods
715 cutree.phylo <- function(tree, k = NULL, h = NULL, ...) {
716 cutree(as.dendrogram(tree), k = k, h = h, ...)
717 }
718
719
720 # ' @S3method cutree phylo
721 #' @export
722 #' @rdname cutree-methods
723 cutree.phylo <- function(tree, k = NULL, h = NULL, ...) {
724 cutree(as.dendrogram(tree), k = k, h = h, ...)
725 }
726
727 # ' @S3method cutree phylo
728 #' @export
729 #' @rdname cutree-methods
730 cutree.agnes <- function(tree, k = NULL, h = NULL, ...) {
731 cutree(as.dendrogram(tree), k = k, h = h, ...)
732 }
733 # stats::cutree
734
735 #' @export
736 #' @rdname cutree-methods
737 cutree.diana <- function(tree, k = NULL, h = NULL, ...) {
738 cutree(as.dendrogram(tree), k = k, h = h, ...)
739 }
740
741
742 # In "cutree.dendrogram" I use "tree" instead of "dend" - in order to stay compatible with stats:cutree
743
744
745 # ' @S3method cutree dendrogram
746 #' @export
747 #' @rdname cutree-methods
748 cutree.dendrogram <- function(tree, k = NULL, h = NULL,
749 dend_heights_per_k = NULL,
750 use_labels_not_values = TRUE,
751 order_clusters_as_data = TRUE,
752 # sort_cluster_numbers = TRUE,
753 warn = dendextend_options("warn"),
754 try_cutree_hclust = TRUE,
755 NA_to_0L = TRUE,
756 ...) {
757 sort_cluster_numbers <- TRUE
758
759 # warnings and stopping rules:
760 if (!is.dendrogram(tree)) stop("tree should be of class dendrogram (and for some reason - it is not)")
761 if (is.null(k) && is.null(h)) stop("Neither k nor h were specified")
762 if (!is.null(k) && !is.null(h)) {
763 if (warn) warning("Both k and h were specified - using k as default
764 (consider using only h or k in order to avoid confusions)")
765 h <- NULL
766 }
767
768
769 # If it is possible to use cutree.hclust - we will!
770 # this would be faster, especially when using k.
771 # and if it doesn't, we would fall back on our function
772 if (try_cutree_hclust) {
773
774 # Fixed the case when order.dendrogram is not the numbers it should
775 # Replacing the order tips with their rank. (otherwise, cutree will CRASH R <= 3.0.1)
776 order_tree <- order.dendrogram(tree)
777 if (!all(order_tree %in% seq_along(order_tree))) {
778 if (warn) {
779 warning("rank() was used for the leaves order number! \nExplenation: leaves tip number (the order), and the ranks of these numbers - are not equal.\n The tree was probably subsetted, pruned and/or merged with other trees- and now the order \n labels don't make so much sense (hence, the rank on them was used).")
780 warning("Here is the cluster order vector (from the tree tips) \n", paste(order_tree, collapse = ", "), "\n")
781 }
782 tree <- rank_order.dendrogram(tree)
783 # order.dendrogram(tree) <- rank(order_tree, ties.method = "first") # we use the "first" ties method - to handle the cases of ties in the ranks (after splits/merges with other trees)
784 }
785
786 # if we succeed (tryCatch) in turning it into hclust - use it!
787 # if not - go on with the function.
788 hclust_tree <- tryCatch(
789 as.hclust(tree),
790 error = function(e) FALSE
791 )
792
793 if (is.hclust(hclust_tree)) {
794 return(cutree(
795 tree = hclust_tree, k = k, h = h,
796 order_clusters_as_data = order_clusters_as_data,
797 # sort_cluster_numbers = sort_cluster_numbers,
798 ...
799 ))
800 }
801 }
802
803
804
805 if (!is.null(k)) {
806 # cluster_vec <- cutree_1k.dendrogram(tree, k,...) # NO, this would only work for scalars...
807
808 if (is.null(dend_heights_per_k)) {
809 # since this is a step which takes a long time, If possible, I'd rather supply this to the function, so to make sure it runs faster...
810 dend_heights_per_k <- heights_per_k.dendrogram(tree)
811 }
812 cutree_per_k <- function(x, tree, ...) cutree_1k.dendrogram(k = x, dend = tree, ...)
813 clusters <- sapply(
814 X = k, FUN = cutree_per_k,
815 tree = tree,
816 dend_heights_per_k = dend_heights_per_k,
817 use_labels_not_values = use_labels_not_values,
818 order_clusters_as_data = order_clusters_as_data,
819 warn = warn,
820 ...
821 )
822 colnames(clusters) <- k
823 }
824
825 # What to do in case h is supplied
826 if (!is.null(h)) {
827 # cluster_vec <- cutree_1h.dendrogram(tree, h,...) # nope...
828 cutree_per_h <- function(x, tree, ...) cutree_1h.dendrogram(h = x, dend = tree, ...)
829 clusters <- sapply(
830 X = h, FUN = cutree_per_h,
831 tree = tree,
832 use_labels_not_values = use_labels_not_values,
833 order_clusters_as_data = order_clusters_as_data,
834 warn = warn,
835 ...
836 )
837 colnames(clusters) <- h
838 }
839
840 # return a vector if h/k are scalars:
841 if (ncol(clusters) == 1) clusters <- clusters[, 1] # make it NOT a matrix
842
843 # sort the clusters id
844 if (sort_cluster_numbers) clusters <- sort_levels_values(clusters, force_integer = TRUE, warn = FALSE)
845 # we know that cluster id is an integer, so it is fine to use force_integer = TRUE
846
847 if (any(is.na(clusters))) warning("It is impossible to produce a one-to-one cut for the k/h you specidied. 0's have been introduced. Note that this result would be different from R's default cutree output.")
848
849 if (NA_to_0L) clusters[is.na(clusters)] <- 0L
850
851 return(clusters)
852 }
853
854
855
856
857
858 # if(FALSE) {
859 # library(dendextend)
860
861 # set.seed(23235)
862 # ss <- sample(1:150, 10 )
863 # hc1 <- hclust(dist(iris[ss,-5]), "com")
864 # dend1 <- as.dendrogram(hc1)
865
866 ## does not give the same results!
867 # cutree(dend1, k=2:3, order_clusters_as_data=TRUE, try_cutree_hclust=FALSE, sort_cluster_numbers=FALSE)
868
869 ## this gives the same results as the default:
870 # cutree.hclust(as.hclust(dend1), k = 3, order_clusters_as_data=TRUE, sort_cluster_numbers=FALSE)
871 # stats::cutree(as.hclust(dend1), k = 3)
872 ## but not for dendrogram:
873 # cutree(dend1, k=3, order_clusters_as_data=TRUE, try_cutree_hclust=FALSE, sort_cluster_numbers=TRUE)
874 # cutree(dend1, k=3, order_clusters_as_data=TRUE, try_cutree_hclust=FALSE, sort_cluster_numbers=FALSE)
875
876
877 ## this gives the same results as the default:
878 # cutree.hclust(as.hclust(dend1), k = 3, order_clusters_as_data=TRUE, sort_cluster_numbers=TRUE)
879 # stats::cutree(as.hclust(dend1), k = 3)
880 # stats::cutree(hc1, k = 3)
881 # cutree.dendrogram(dend1, k=3, order_clusters_as_data=TRUE, try_cutree_hclust=FALSE,
882 # sort_cluster_numbers=TRUE)
883
884
885 # }
886
887
888
889
890
891
892
893
894
895 ### TODO:
896 ### possible functions to add:
897 # ultrametric
898 # is.ultrametric(as.phylo(as.hclust(dend)))
899 # is.ultrametric(as.phylo(as.hclust(hang.dendrogram(dend))))
900 # plot(as.phylo(as.hclust(hang.dendrogram(dend))))
901 # is.ultrametric(as.phylo(as.hclust(dend, hang = 2)))
902 # is.binary.tree
903
904
905
906
907
908
909 ## ----------------------
910 ## examples:
911 # hc <- hclust(dist(USArrests[c(1:3,7,5),]), "ave")
912 # dhc <- as.dendrogram(hc)
913 # str(dhc)
914 # plot(hc)
915
916 # cutree(dhc, h = 50)
917 # cutree.dendrogram(dhc, h = 50)
918 # cutree.dendrogram(dhc, k = 3) # same output
919 # cutree.dendrogram(dhc, k = 3,h = 50) # conflicting options - using h as default
920 # cutree.dendrogram(dhc, k = 10) # handaling the case were k is not a viable number of clusters
921
922 ## showing another case were k is not an option
923 # attr(dhc[[2]][[1]], "height") <- 23.2
924 # attr(dhc[[2]][[2]], "height") <- 23.2
925 # plot(dhc)
926 # is.ultrametric(as.phylo(dhc))
927 # cutree.dendrogram(dhc, k = 4) # handaling the case were k is not a viable number of clusters
928 # cutree.dendrogram(dhc, k = 3.2) # handaling the case were k is not a viable number of clusters
929
930
931 # heights_per_k.dendrogram(dhc)