Skip to content

Instantly share code, notes, and snippets.

@josephwb
Created April 13, 2018 10:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephwb/1aa5082c80945bf9cf939184b7d816ce to your computer and use it in GitHub Desktop.
Save josephwb/1aa5082c80945bf9cf939184b7d816ce to your computer and use it in GitHub Desktop.
(R) From a larger tree, extract the subtree induced from a specified set of tips. Requires ape.
# extract subtree induced from a set of tips
subtree.induced <- function (phy, tip) {
if (!inherits(phy, "phylo")) {
stop("object \"phy\" is not of class \"phylo\"");
}
Ntip <- length(phy$tip.label);
# convert to indices if strings passed in
if (is.character(tip)) {
idx <- match(tip, phy$tip.label);
# stop on bad tip names
# alternative is to warn but probably not ideal
if (any(is.na(idx))) {
um <- c("umatched tip labels:\n", paste(tip[which(is.na(idx))], collapse=" "));
stop(um);
}
tip <- idx;
} else {
# check that passed in indices are all valid
out.of.range <- tip > Ntip;
if (any(out.of.range)) {
warning("some tip numbers were larger than the number of tips: they were ignored");
tip <- tip[!out.of.range];
}
}
# get complement tip indices to drop
toDrop <- setdiff(1:Ntip, tip);
drop.tip(phy, toDrop);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment