Skip to content

Instantly share code, notes, and snippets.

@chasemc
Last active May 7, 2020 22:40
Show Gist options
  • Save chasemc/3341b3a7914ce19aceaf64168f9d779b to your computer and use it in GitHub Desktop.
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)
# 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