Debian Codegraph @

R/labels.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
21
22
23
24
25
26
27
28 #' ###################
29 ## Adding labels assignment as an S3 method (and extending it to include hclust)
30 ## Also order labels
31
32
33 ### Includes the functions:
34 # labels<-.default
35 # labels<-.dendrogram
36 # labels.hclust
37 # labels<-.hclust
38 # labels.matrix
39 # labels<-.matrix
40 #
41 # "order.dendrogram<-"
42
43
44
45
46
47 # turning label insertion function into a method:
48
49 #' @title "label" assignment operator
50 #' @export
51 #' @rdname labels-assign
52 #' @description "label" assignment operator for vectors, dendrogram, and hclust classes.
53 #'
54 #' @param object a variable name (possibly quoted) who's label are to be updated
55 #' @param ... parameters passed (not currently in use)
56 #' @param value a value to be assigned to object's label
57 #' @param order default is FALSE. Only relevant for extracting labels from an
58 #' \link{hclust} object (with labels.hclust). Setting order=TRUE will return
59 #' labels in their order in the dendrogram, instead of the riginal labels order
60 #' retained from object$labels - which ususally corresponding to
61 #' the row or column names of the \link{dist} object provided to
62 #' the \link{hclust} function.
63 #' @return The updated object
64 #' @author Gavin Simpson, Tal Galili
65 #' (with some ideas from Gregory Jefferis's dendroextras package)
66 #' @source
67 #' The functions here are based on code by Gavin and kohske from
68 #' (adopted to dendrogram by Tal Galili):
69 #' \url{https://stackoverflow.com/questions/4614223/how-to-have-the-following-work-labelsx-some-value-r-question}
70 #' Also with some ideas from Gregory Jefferis's dendroextras package.
71 #' @seealso \code{\link{labels}}
72 #' @examples
73 #' x <- 1:3
74 #' labels(x)
75 #' labels(x) <- letters[1:3]
76 #' labels(x) # [1] "a" "b" "c"
77 #' x
78 #' # a b c
79 #' # 1 2 3
80 #'
81 #'
82 #' # get("labels<-")
83 #'
84 #' ################
85 #' # Example for using the assignment with dendrogram and hclust objects:
86 #' hc <- hclust(dist(USArrests[1:3, ]), "ave")
87 #' dend <- as.dendrogram(hc)
88 #'
89 #' labels(hc) # "Arizona" "Alabama" "Alaska"
90 #' labels(hc) <- letters[1:3]
91 #' labels(hc) # "a" "b" "c"
92 #' labels(dend) # "Arizona" "Alabama" "Alaska"
93 #' labels(dend) <- letters[1:3]
94 #' labels(dend) # "a" "b" "c"
95 #' suppressWarnings(labels(dend) <- LETTERS[1:2]) # will produce a warning
96 #' labels(dend) # "A" "B" "A"
97 #' labels(dend) <- LETTERS[4:6] # will replace the labels correctly
98 #' # (the fact the tree had duplicate labels will not cause a problem)
99 #' labels(dend) # "D" "E" "F"
100 `labels<-` <- function(object, ..., value) {
101 UseMethod("labels<-")
102 }
103
104 # example("labels<-")
105 # ?"labels<-"
106
107
108 #' @export
109 #' @rdname labels-assign
110 `labels<-.default` <- function(object, ..., value) {
111 if (length(value) < length(object)) {
112 warning("The lengths of the new labels is shorter than the length of the object - labels are recycled.")
113 names(object) <- rep(value, length.out = length(object)) # I assume here that if ever labels will be used in the naive sense, it would be as a synonym to "names"
114 } else {
115 names(object) <- value # I assume here that if ever labels will be used in the naive sense, it would be as a synonym to "names"
116 }
117 object
118 }
119
120
121
122 #' @export
123 #' @rdname labels-assign
124 `labels<-.dendrogram` <- function(object, ..., value) {
125 # credit for the help on how to write this type of function goes to:
126 # Gavin Simpson and also kohske, see here:
127 # https://stackoverflow.com/questions/4614223/how-to-have-the-following-work-labelsx-some-value-r-question
128
129 if (missing(value)) {
130 if (dendextend_options("warn")) warning("value is missing, returning the dendrogram as is")
131 return(object)
132 }
133
134
135 # deals with wrong length of new labels VS tree size
136 # new_labels <- as.character(value) # I shouldn't force this to a character
137 new_labels <- value
138 new_labels_length <- length(new_labels)
139 leaves_length <- nleaves(object) # labels(object) # it will be faster to use order.dendrogram than labels...
140 if (new_labels_length < leaves_length) {
141 warning("The lengths of the new labels is shorter than the number of leaves in the dendrogram - labels are recycled.")
142 new_labels <- rep(new_labels, length.out = leaves_length)
143 }
144
145 .change.label.LTR <- function(dend_node) {
146 if (is.leaf(dend_node)) {
147 attr(dend_node, "label") <- new_labels[i_leaf_number]
148 i_leaf_number <<- i_leaf_number + 1 # this saves us from cases of duplicate enteries...
149 }
150 return(unclass(dend_node)) # the "unclass" is important since dendrapply adds the dendrogram class to each node (which is irrelevent)
151 }
152
153 i_leaf_number <- 1
154 new_dend_object <- dendrapply(object, .change.label.LTR)
155 class(new_dend_object) <- "dendrogram"
156
157 return(new_dend_object)
158 }
159
160
161
162 #' @export
163 #' @rdname labels-assign
164 labels.hclust <- function(object, order = TRUE, ...) {
165 if (order) {
166 labels_obj <- as.character(object$labels[object$order])
167 } else {
168 labels_obj <- as.character(object$labels)
169 }
170
171 return(labels_obj)
172 }
173
174
175 #' @export
176 #' @rdname labels-assign
177 `labels<-.hclust` <- function(object, ..., value) {
178 if (length(value) < length(object$labels)) {
179 warning("The lengths of the new labels is shorter than the number of leaves in the hclust - labels are recycled.")
180 }
181
182 object$labels[object$order] <- value # I assume here that if ever labels will be used in the naive sense, it would be as a synonym to "names"
183 return(object)
184 }
185
186
187
188 #' @export
189 #' @rdname labels-assign
190 labels.phylo <- function(object, ...) {
191 object$tip.label
192 }
193
194
195
196
197 #' @export
198 #' @rdname labels-assign
199 `labels<-.phylo` <- function(object, ..., value) {
200 if (missing(value)) {
201 if (dendextend_options("warn")) warning("value is missing, returning the dendrogram as is")
202 return(object)
203 }
204
205
206 # deals with wrong length of new labels VS tree size
207 new_labels <- as.character(value)
208 new_labels_length <- length(new_labels)
209 leaves_length <- nleaves(object) # labels(object) # it will be faster to use order.dendrogram than labels...
210 if (new_labels_length < leaves_length) {
211 warning("The lengths of the new labels is shorter than the number of leaves in the dendrogram - labels are recycled.")
212 new_labels <- rep(new_labels, length.out = leaves_length)
213 }
214
215 object$tip.label <- new_labels
216
217 return(object)
218 }
219
220
221
222
223 #
224 # # ' @title "label" assignment operator for matrix class
225 # # ' @S3method labels matrix
226 # # ' @export
227 # labels.matrix <- function(object, which = c("colnames","rownames"), ...) {
228 # if(missing(which))
229 # which <- "colnames"
230 # which <- match.arg(which)
231 # if(which == "colnames") {
232 # out <- colnames(object)
233 # } else {
234 # out <- rownames(object)
235 # }
236 # out
237 # }
238 # # example("labels.matrix")
239 # # ?"labels.matrix"
240 #
241 # # ' @title "label" assignment operator - matrix
242 # # ' @S3method labels<- matrix
243 # # ' @export
244 # # ' @keywords internal
245 # 'labels<-.matrix' <- function(object, which = c("colnames","rownames"), ..., value) {
246 # if(missing(which))
247 # which <- "colnames"
248 # which <- match.arg(which)
249 #
250 # # I'm using ncol and nrow instead of length(colnames(object))
251 # # since if the object has no colnames, their length will be 0
252 #
253 # if(which == "colnames") {
254 #
255 # if(length(value) < ncol(object)) {
256 # warning("The lengths of the new labels is shorter than the length of the object's colnames - labels are recycled.")
257 # colnames(object) <- rep(value, length.out = ncol(object)) # I assume here that if ever labels will be used in the naive sense, it would be as a synonym to "names"
258 # } else {
259 # colnames(object) <- value # I assume here that if ever labels will be used in the naive sense, it would be as a synonym to "names"
260 # }
261 #
262 # } else {
263 #
264 # if(length(value) < nrow(object)) {
265 # warning("The lengths of the new labels is shorter than the length of the object's rownames - labels are recycled.")
266 # rownames(object) <- rep(value, length.out = nrow(object)) # I assume here that if ever labels will be used in the naive sense, it would be as a synonym to "names"
267 # } else {
268 # rownames(object) <- value # I assume here that if ever labels will be used in the naive sense, it would be as a synonym to "names"
269 # }
270 #
271 # }
272 # object
273 # }
274 #
275 #
276
277
278
279
280
281 #' @title order.dendrogram<- assignment operator
282 #' @export
283 #' @rdname order.dendrogram-assign
284 #' @description order.dendrogram<- assignment operator. This is useful in cases where some object is turned into a dendrogram but its leaves values (the order) are all mixed up.
285 #' @param object a variable name (possibly quoted) who's label are to be updated
286 #' @param ... parameters passed (not currently in use)
287 #' @param value a value to be assigned to object's leaves value (their "order")
288 #' @return dendrogram with updated order leaves values
289 #' @seealso \code{\link{order.dendrogram}}, \code{\link{labels<-}}
290 #' @examples
291 #' ################
292 #' # Example for using the assignment with dendrogram and hclust objects:
293 #' hc <- hclust(dist(USArrests[1:4, ]), "ave")
294 #' dend <- as.dendrogram(hc)
295 #'
296 #' str(dend)
297 #' order.dendrogram(dend) # 4 3 1 2
298 #' order.dendrogram(dend) <- 1:4
299 #' order.dendrogram(dend) # 1 2 3 4
300 #' str(dend) # the structure is still fine.
301 #'
302 #' # This function is very useful if we try playing with subtrees
303 #' # For example:
304 #' hc <- hclust(dist(USArrests[1:6, ]), "ave")
305 #' dend <- as.dendrogram(hc)
306 #' sub_dend <- dend[[1]]
307 #' order.dendrogram(sub_dend) # 4 6
308 #' # now using as.hclust(sub_dend) will cause trouble:
309 #' # labels(as.hclust(sub_dend)) # As of R 3.1.1-patched - this will produce an Error (as it should) :)
310 #' # let's fix it:
311 #'
312 #' order.dendrogram(sub_dend) <- rank(order.dendrogram(sub_dend), ties.method = "first")
313 #' labels(as.hclust(sub_dend)) # We now have labels :)
314 `order.dendrogram<-` <- function(object, ..., value) {
315
316 # notice that: is.integer(as.numeric(1L)) == FALSE
317 # is.numeric(1L) == TRUE
318 # but the next line will not be triggered if value is an integer!
319 if (!is.numeric(value)) {
320 warning("'value' is not numeric - coerced using as.numeric")
321 value <- as.numeric(value)
322 }
323 if (!is.integer(value)) {
324 warning("'value' is not integer - coerced using as.integer")
325 value <- as.integer(value)
326 }
327 new_order_values <- value
328
329 new_labels_length <- length(new_order_values)
330 leaves_length <- nleaves(object) # labels(object) # it will be faster to use order.dendrogram than labels...
331
332 if (new_labels_length < leaves_length) {
333 warning("The lengths of the new labels is shorter than the number of leaves in the dendrogram - labels are recycled.")
334 new_order_values <- rep(new_order_values, length.out = leaves_length)
335 }
336
337
338 # I can't think of a case were someone would like to use non unique values. But just in case - I will warn them that they are doing so...
339 if (any(duplicated(new_order_values))) {
340 warning("The value you wish to insert into the dendrogram 'objects' has duplicate values. Often you are likely to prefer unique values in your vector. So be sure to check that you've used the correct vector here...")
341 }
342 # any(duplicated(c(1:4, 2)))
343
344
345 .change_order_LTR <- function(dend_node) {
346 if (is.leaf(dend_node)) {
347 attr_backup <- attributes(dend_node)
348 dend_node <- new_order_values[i_leaf_number]
349 attributes(dend_node) <- attr_backup # fix attributes
350 i_leaf_number <<- i_leaf_number + 1 # this saves us from cases of duplicate enteries...
351 }
352 return(unclass(dend_node))
353 }
354
355 i_leaf_number <- 1
356 new_dend_object <- dendrapply(object, .change_order_LTR)
357 class(new_dend_object) <- "dendrogram"
358
359 return(new_dend_object)
360 }
361
362
363
364 # methods("labels")
365 # methods("labels<-")
366 # example("labels.matrix")
367
368
369
370 #' @title Ordering of the Leaves in a hclust Dendrogram
371 #' @description Ordering of the Leaves in a hclust Dendrogram. Like \link{order.dendrogram}.
372 #' @export
373 #' @param x ab hclust object a distance matrix.
374 #' @param ... Ignored.
375 #' @seealso
376 #' \link{order.dendrogram}
377 #' @return
378 #' A vector with length equal to the number of
379 #' leaves in the hclust dendrogram is returned.
380 #' From r <- order.hclust(), each element is
381 #' the index into the original data
382 #' (from which the hclust was computed).
383 #'
384 #' @examples
385 #'
386 #' set.seed(23235)
387 #' ss <- sample(1:150, 10)
388 #' hc <- iris[ss, -5] %>%
389 #' dist() %>%
390 #' hclust()
391 #' # dend <- hc %>% as.dendrogram
392 #' order.hclust(hc)
393 order.hclust <- function(x, ...) {
394 if (!is.hclust(x)) stop("x is not a hclust object.")
395 x$order
396 }
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420 #' @title Set/place new labels in a dendrogram
421 #' @export
422 #' @description
423 #' Convenience functions for updating the labels of a dendrogram.
424 #' set_labels and place_labels differs in their assumption about the order of the labels.
425 #' * set_labels assumes the labels are in the same order as that of the labels in the dendrogram.
426 #' * place_labels assumes the labels has the same order as that of the items in the original data matrix.
427 #' This is useful for renaming labels based on some other columns in the data matrix.
428 #'
429 #' @aliases
430 #' place_labels
431 #' @param dend a \link{dendrogram} object
432 #' @param labels A vector of values to insert in the labels of a dendrogram.
433 #' @param ... Currently ignored.
434 #' @return The updated \link{dendrogram} object
435 #' @author Tal Galili, Garrett Grolemund
436 #' @seealso \code{\link{labels}}, \code{\link{set}}
437 #' @examples
438 #'
439 #' ss <- c(
440 #' 50, 114, 17, 102, 76, 10, 107, 84, 31, 37, 49, 106, 44, 119,
441 #' 104, 145, 67, 85, 12, 77, 22, 136, 38, 135, 70
442 #' )
443 #'
444 #' small_iris <- iris[ss, ]
445 #'
446 #' small_iris[, -5] %>%
447 #' dist() %>%
448 #' hclust(method = "complete") %>%
449 #' as.dendrogram() %>%
450 #' color_branches(k = 3) %>%
451 #' color_labels(k = 3) %>%
452 #' plot()
453 #'
454 #' # example for using place_labels
455 #' small_iris[, -5] %>%
456 #' dist() %>%
457 #' hclust(method = "complete") %>%
458 #' as.dendrogram() %>%
459 #' color_branches(k = 3) %>%
460 #' color_labels(k = 3) %>%
461 #' place_labels(paste(small_iris$Species, 1:25, sep = "_")) %>%
462 #' plot()
463 #'
464 #' # example for using set_labels
465 #' small_iris[, -5] %>%
466 #' dist() %>%
467 #' hclust(method = "complete") %>%
468 #' as.dendrogram() %>%
469 #' color_branches(k = 3) %>%
470 #' color_labels(k = 3) %>%
471 #' set_labels(1:25) %>%
472 #' plot()
473 set_labels <- function(dend, labels, ...) {
474 labels(dend) <- labels
475 dend
476 }
477
478
479 #' @export
480 place_labels <- function(dend, labels, ...) {
481 set_labels(dend, labels[order.dendrogram(dend)])
482 }