Debian Codegraph @

R/cor_bakers_gamma.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 #' @title Find lowest common branch were the two items are shared
22 #' @export
23 #' @description
24 #' Given two vectors, for two items, of cluster belonging - the function finds
25 #' the lowest branch (e.g: largest number of k clusters) for which the two
26 #' items are in the same cluster for the two trees.
27 #' @param item1 a named numeric vector (of cluster group with names of k level)
28 #' @param item2 a named numeric vector (of cluster group with names of k level)
29 #' @param ... not used
30 #' @seealso
31 #' \link{cor_bakers_gamma}
32 #' @return
33 #' The first location (from left) where the two vectors have the same A dendrogram, after adjusting the members attr in all of its nodes.
34 #' @examples
35 #'
36 #' item1 <- structure(c(1L, 1L, 1L, 1L), .Names = c("1", "2", "3", "4"))
37 #' item2 <- structure(c(1L, 1L, 2L, 2L), .Names = c("1", "2", "3", "4"))
38 #' lowest_common_branch(item1, item2)
39 lowest_common_branch <- function(item1, item2, ...) {
40 # for two rows of cluster belonging,
41 # this finds all the cases where the two items are identical (e.g: belong to the same branch)
42 # Then it takes the most extreme value (lowest branch) where this happens
43 # and finally - it extracts the level of that lowest brnach (names) and turn it to be numeric
44 value <- as.numeric(names(tail(which(item1 == item2), 1)))
45 if (length(value) == 0) value <- 0
46 return(value)
47 }
48
49
50 #' @title Bakers Gamma for two k matrices
51 #' @description Bakers Gamma for two k matrices
52 #' @param k_matrix_dend1 a matrix of k cluster groupings from a dendrogram
53 #' @param k_matrix_dend2 a (second) matrix of k cluster groupings from a dendrogram
54 #' @param to_plot logical (FALSE). Should a scaterplot be plotted, showing the
55 #' correlation between the lowest shared branch between two items in the two
56 #' compared trees.
57 #' @param ... not used
58 #' @seealso
59 #' \link{cor_bakers_gamma}
60 #' @return
61 #' Baker's Gamma coefficient.
62 bakers_gamma_for_2_k_matrix <- function(k_matrix_dend1, k_matrix_dend2, to_plot = FALSE, ...) {
63 if (dim(k_matrix_dend1)[1] != dim(k_matrix_dend2)[1]) stop("The k_matrixes seems to show a different number of items - we can not compare trees in this case!")
64 if (!all(sort(rownames(k_matrix_dend1)) == sort(rownames(k_matrix_dend2)))) { # we are using "sort" since the rownames may be of different order - depending on the way the two trees were constructed.
65 print(paste("Item names (rownames) of k_matrix_dend1:", rownames(k_matrix_dend1)))
66 print(paste("Item names (rownames) of k_matrix_dend2:", rownames(k_matrix_dend2)))
67 stop("The k_matrixes seems to have different item names - \n we can not compare trees in this case! \n Consider using use_labels_not_values = T (or F) in cutree")
68 }
69
70 all_combinations_of_items <- t(combn(seq_len(dim(k_matrix_dend1)[1]), 2))
71 number_of_combinations_of_items <- dim(all_combinations_of_items)[1]
72
73
74 cor_mat <- matrix(0, number_of_combinations_of_items, 2)
75
76
77 for (i in seq_len(number_of_combinations_of_items))
78 {
79 item_id_1_name <- rownames(k_matrix_dend1)[all_combinations_of_items[i, 1]]
80 item_id_2_name <- rownames(k_matrix_dend1)[all_combinations_of_items[i, 2]]
81 # The names must be identical in both trees - we've made a stopping rule for that already.
82 item1 <- k_matrix_dend1[item_id_1_name, ]
83 item2 <- k_matrix_dend1[item_id_2_name, ]
84 # print(paste(i, item1, item2))
85 cor_mat[i, 1] <- lowest_common_branch(item1, item2)
86
87 item1 <- k_matrix_dend2[item_id_1_name, ]
88 item2 <- k_matrix_dend2[item_id_2_name, ]
89 cor_mat[i, 2] <- lowest_common_branch(item1, item2)
90 }
91
92 COR_object <- cor(cor_mat[, 1], cor_mat[, 2], method = "spearman")
93 if (is.na(COR_object)) COR_object <- 1 # because this is NA only if the two vectors are identical
94 # that happens only when the two trees have only leaves. Which is o.k. to define as correlation of 1.
95
96 if (to_plot) {
97 plot(cor_mat, sub = paste("COR =", round(COR_object, 4)))
98 }
99
100 return(COR_object)
101 }
102
103
104
105
106
107
108
109
110 #' @title Baker's Gamma correlation coefficient
111 #' @name cor_bakers_gamma
112 #' @export
113 #' @aliases
114 #' cor_bakers_gamma.dendrogram
115 #' cor_bakers_gamma.hclust
116 #' cor_bakers_gamma.dendlist
117 #'
118 #'
119 #' @description
120 #' Calculate Baker's Gamma correlation coefficient for two trees
121 #' (also known as Goodman-Kruskal-gamma index).
122 #'
123 #' Assumes the labels in the two trees fully match. If they do not
124 #' please first use \link{intersect_trees} to have them matched.
125 #'
126 #' WARNING: this can be quite slow for medium/large trees.
127 #'
128 #' @param dend1 a tree (dendrogram/hclust/phylo)
129 #' @param dend2 a tree (dendrogram/hclust/phylo)
130 #' @param use_labels_not_values logical (TRUE). Should labels be used in the
131 #' k matrix when using cutree? Set to FALSE will make the function a bit faster
132 #' BUT, it assumes the two trees have the exact same leaves order values for
133 #' each labels. This can be assured by using \link{match_order_by_labels}.
134 #' @param to_plot logical (FALSE). Passed to \link{bakers_gamma_for_2_k_matrix}
135 #' @param warn logical (default from dendextend_options("warn") is FALSE).
136 #' Set if warning are to be issued, it is safer to keep this at TRUE,
137 #' but for keeping the noise down, the default is FALSE.
138 #' should a warning be issued when using \link[dendextend]{cutree}?
139 #' @param ... Passed to \link[dendextend]{cutree}.
140 #' @param which an integer vector of length 2, indicating
141 #' which of the trees in the dendlist object should be plotted (relevant for dendlist)
142 #'
143 #' @details
144 #' Baker's Gamma (see reference) is a measure of accosiation (similarity)
145 #' between two trees of heirarchical clustering (dendrograms).
146 #'
147 #' It is calculated by taking two items, and see what is the heighst
148 #' possible level of k (number of cluster groups created when cutting the tree)
149 #' for which the two item still belongs to the same tree. That k is returned,
150 #' and the same is done for these two items for the second tree.
151 #' There are n over 2 combinations of such pairs of items from the items in
152 #' the tree, and all of these numbers are calculated for each of the two trees.
153 #' Then, these two sets of numbers (a set for the items in each tree)
154 #' are paired according to the pairs of items compared, and a spearman
155 #' correlation is calculated.
156 #'
157 #' The value can range between -1 to 1. With near 0 values meaning that
158 #' the two trees are not statistically similar.
159 #' For exact p-value one should result to a permutation test. One such option
160 #' will be to permute over the labels of one tree many times, and calculating
161 #' the distriubtion under the null hypothesis (keeping the trees topologies
162 #' constant).
163 #'
164 #' Notice that this measure is not affected by the height of a branch but only
165 #' of its relative position compared with other branches.
166 #'
167 #' @seealso
168 #' \link{cor_cophenetic}
169 #' @return
170 #' Baker's Gamma association Index between two trees (a number between -1 to 1)
171 #'
172 #' @references
173 #'
174 #' Baker, F. B., Stability of Two Hierarchical Grouping Techniques Case
175 #' 1: Sensitivity to Data Errors. Journal of the American Statistical
176 #' Association, 69(346), 440 (1974).
177 #'
178 #' @examples
179 #'
180 #' \dontrun{
181 #'
182 #' set.seed(23235)
183 #' ss <- sample(1:150, 10)
184 #' hc1 <- hclust(dist(iris[ss, -5]), "com")
185 #' hc2 <- hclust(dist(iris[ss, -5]), "single")
186 #' dend1 <- as.dendrogram(hc1)
187 #' dend2 <- as.dendrogram(hc2)
188 #' # cutree(dend1)
189 #'
190 #' cor_bakers_gamma(hc1, hc2)
191 #' cor_bakers_gamma(dend1, dend2)
192 #'
193 #' dend1 <- match_order_by_labels(dend1, dend2) # if you are not sure
194 #' cor_bakers_gamma(dend1, dend2, use_labels_not_values = FALSE)
195 #'
196 #' library(microbenchmark)
197 #' microbenchmark(
198 #' with_labels = cor_bakers_gamma(dend1, dend2, try_cutree_hclust = FALSE),
199 #' with_values = cor_bakers_gamma(dend1, dend2,
200 #' use_labels_not_values = FALSE, try_cutree_hclust = FALSE
201 #' ),
202 #' times = 10
203 #' )
204 #'
205 #'
206 #' cor_bakers_gamma(dend1, dend1, use_labels_not_values = FALSE)
207 #' cor_bakers_gamma(dend1, dend1, use_labels_not_values = TRUE)
208 #' }
209 #'
210 cor_bakers_gamma <- function(dend1, ...) {
211 UseMethod("cor_bakers_gamma")
212 }
213
214
215 #' @export
216 #' @rdname cor_bakers_gamma
217 cor_bakers_gamma.default <- function(dend1, dend2, ...) {
218 dend1 <- as.dendrogram(dend1)
219 dend2 <- as.dendrogram(dend2)
220 cor_bakers_gamma(dend1, dend2, ...)
221 }
222
223 #' @export
224 #' @rdname cor_bakers_gamma
225 cor_bakers_gamma.dendrogram <- function(dend1, dend2, use_labels_not_values = TRUE, to_plot = FALSE, warn = dendextend_options("warn"), ...) {
226 k_matrix_dend1 <- cutree(dend1, k = 1:nleaves(dend1), use_labels_not_values = use_labels_not_values, warn = warn, ...)
227 k_matrix_dend2 <- cutree(dend2, k = 1:nleaves(dend2), use_labels_not_values = use_labels_not_values, warn = warn, ...)
228 bakers_gamma <- bakers_gamma_for_2_k_matrix(k_matrix_dend1, k_matrix_dend2, to_plot = to_plot)
229 return(bakers_gamma)
230 }
231
232
233 #' @export
234 #' @rdname cor_bakers_gamma
235 cor_bakers_gamma.hclust <- function(dend1, dend2, use_labels_not_values = TRUE, to_plot = FALSE, warn = dendextend_options("warn"), ...) {
236 k_matrix_dend1 <- cutree(dend1, k = 1:nleaves(dend1), use_labels_not_values = use_labels_not_values, warn = warn, ...)
237 k_matrix_dend2 <- cutree(dend2, k = 1:nleaves(dend2), use_labels_not_values = use_labels_not_values, warn = warn, ...)
238 bakers_gamma <- bakers_gamma_for_2_k_matrix(k_matrix_dend1, k_matrix_dend2, to_plot = to_plot)
239 return(bakers_gamma)
240 }
241
242
243
244 #' @export
245 #' @rdname cor_bakers_gamma
246 cor_bakers_gamma.dendlist <- function(dend1, which = c(1L, 2L), ...) {
247 cor_bakers_gamma(dend1[[which[1]]], dend1[[which[2]]], ...)
248 }
249
250
251
252 # k_matrix_dend1 <- cutree(hc1, k = 1:nleaves(hc1))
253 # k_matrix_dend2 <- cutree(hc2, k = 1:nleaves(hc1))
254 # library(compiler)
255 # enableJIT(3)
256 # system.time(bakers_gamma_for_2_k_matrix(k_matrix_dend1, k_matrix_dend2))
257 # before: 2.37
258 # after: 1.97