R/treefromtaxonomy.R

Defines functions treefromtaxonomy

Documented in treefromtaxonomy

################# treefromtaxonomy       #################
###               Franz-S. Krah                        ###
treefromtaxonomy <- function(tax=c, include="auto", prune="gen", method="Grafen", power=1)
{
  # prune taxonomy to a provided taxonomy level
  if(!prune==FALSE){
    tax <- tax[match(unique(tax[,prune]),tax[,prune]),]
  }
  # make all columns factors
  col_names <- names(tax)
  tax[,col_names] <- lapply(tax[,col_names] , factor)
  # automatically choose the maximum resolution for the tree
  if(include=="auto")
  {
    tax_levels <- sapply(tax, function(x) length(levels(x)))
    first <- names(which(tax_levels>1)[1])
    following <- names(which(tax_levels>1)[2:length(tax_levels)])
    following <- na.omit(following)
    tax_include <- c(first, following)
    tax_include <- paste("~", paste(tax_include, sep="", collapse="/"))
  }
  # provide own vector with taxonomy names to be included
  else{tax_include <- include}
  tree <- as.phylo(eval(parse(text=tax_include)), data= tax)
  # alter tip.labels to pruned taxonomy level 
  if(!prune==FALSE){
    tree$tip.label <- as.character(tax[,prune][tax[,"spec"] %in% tree$tip.label])
  }
  # provide branch length by the ape function 'compute.brlen'
  tree <- compute.brlen(tree, method = method, power = power)
  return(tree)
}
FranzKrah/seta documentation built on Sept. 15, 2017, 4:50 p.m.