R/node_conversion.R

Defines functions ToNewick as.Node

Documented in as.Node ToNewick

#' Convert an object to a \code{data.tree} data structure
#' 
#' @param x The object to be converted
#' @param ... Additional arguments
#' 
#' @family as.Node
#' 
#' @export
as.Node <- function(x, ...) {
  UseMethod("as.Node")
}


  


#' Write a \code{data.tree} structure to Newick notation
#' 
#' To read from Newick, you can use the \code{ape} package, and convert the resulting \code{phylo}
#' object to a \code{data.tree} structure.
#' 
#' @param node The root \code{Node} of a tree or sub-tree to be converted
#' @param heightAttribute The attribute (field name, method, or function) storing or calculating the height for each \code{Node}
#' @param ... parameters that will be passed on the the heightAttributeName, in case it is a function
#' 
#' @import stringi
#' 
#' @examples
#' data(acme)
#' ToNewick(acme)
#' ToNewick(acme, heightAttribute = NULL)
#' ToNewick(acme, heightAttribute = function(x) DefaultPlotHeight(x, 200))
#' ToNewick(acme, rootHeight = 200)
#' 
#' @family Conversions from Node
#' 
#' @keywords Newick
#' 
#' @export 
ToNewick <- function(node, heightAttribute = DefaultPlotHeight, ...) {

  deparse <- function(x) {
    name <- stri_replace_all_fixed(x$name, " ", "_")
    name <- stri_replace_all_fixed(name, ",", "")
    if(!isRoot(x) && length(heightAttribute) > 0) {
      edge <- GetAttribute(x$parent, heightAttribute, ...) - GetAttribute(x, heightAttribute, ...) 
      me <- paste0(name, ":", edge)
    } else {
      me <- name
    }
    return(me)
  }
  
  Newick <- function(x) {
    if(x$isLeaf) {
      return (deparse(x))
    }
    chNewick <- sapply(x$children, Newick)
    chNewickStr <- paste(chNewick, collapse = ",")
    res <- paste0("(", chNewickStr, ")", deparse(x))
  }
  
  res <- Newick(node)
  res <- paste0(res, ";")
  return (res)
  
}

Try the data.tree package in your browser

Any scripts or data that you put into this service are public.

data.tree documentation built on Nov. 13, 2023, 1:08 a.m.