Last active
May 7, 2020 22:40
-
-
Save chasemc/3341b3a7914ce19aceaf64168f9d779b to your computer and use it in GitHub Desktop.
Find the height of the least common ancestor of two nodes in a dendrogram in R (requires dendextend package)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# install.packages("dendexted") | |
lca_height <- function(dend, | |
input_a, | |
input_b) { | |
subtrees <- dendextend::partition_leaves(dend) | |
find_ancestors <- function(input_labels) { | |
which(sapply(subtrees, function(x) input_labels %in% x)) | |
} | |
ancestors <- lapply(c(input_a, input_b), find_ancestors) | |
# find largest common | |
lca <- ancestors[[1]][max(which(ancestors[[1]] %in% ancestors[[2]]))] | |
# which column represents "evolutionary" height | |
index <- which(sapply(as.data.frame(dendextend::get_nodes_xy(dend)), max) != attributes(dend)$members)[[1]] | |
dendextend::get_nodes_xy(dend)[lca, index] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment