R/datasim_supp.R

Defines functions extract extract.default extract.sim_phylo extract.sim_ex convert.matrix

Documented in convert.matrix extract

# support functions for data simulations. Mostly to work with S3 object. These functions are not exported.

#' @title Extract simluation type specific data
#' @description The extract function to extract data from an S3 object.
#' @param object The object of type \code{MCSim}

extract <- function(object){
  UseMethod('extract')
}

# default
extract.default <- function(object){
  stop("There aren't any recognized types!")
}

# sim_phylo specific method
extract.sim_phylo <- function(object){
  abundance <- object$abundance
  n.spec <- ncol(abundance)
  n.samp <- nrow(abundance)
  tree <- object$tree
  correlation <- object$correlation
  copula <- object$copula
  result <- list(abundance, n.spec, n.samp, tree, correlation, copula)
  names(result) <- c("abundance", "n.spec", "n.samp", "tree", "correlation", "copula")
  return(result)
}

# sim_ex specific method
extract.sim_ex <- function(object){
  abundance <- object$abundance
  tree <- object$tree
  n.spec <- ncol(abundance)
  n.samp <- nrow(abundance)
  rho <- object$rho
  copula <- object$copula
  result <- list(abundance, n.spec, n.samp, rho, copula, tree)
  names(result) <- c("abundance","n.spec", "n.samp", "rho", "copula", "tree")
  return(result)
}

#' @title Convert existing data matrix into a MCSim object of type \code{sim_phylo}
#' @description The function takes a data matrix and a corresponding phylogenetic tree, converting in to type \code{MCSim}
#'     and type \code{sim_phylo} so that internal methods and the \code{outcome.sim} function can be used on real taxonomic data. 
#' @param data The data in matrix format with samples as rows and OTUs as columns  
#' @param tree A phylogenetic tree of newick format loaded in using the \code{ape} package
#' @export
convert.matrix <- function(data, tree){
  correlation <- ape::vcv(tree, corr = TRUE) # generating the correlation matrix
  lower.correlation <- correlation[lower.tri(correlation)]
  abundance <- data
  copula <- copula::normalCopula(param = lower.correlation, dim = ncol(data), dispstr = "un")
  result <- list(abundance = data, copula = copula, tree = tree, correlation = correlation)
  class(result) <- append(class(result), c("MCSim", "sim_phylo"))
  return(result)
}
quangnguyen1995/MCTools documentation built on May 23, 2019, 8:56 a.m.