R/Trans_to_phylo.R

Defines functions Trans_to_phylo

Documented in Trans_to_phylo

#' Convert a LorMe object to a phyloseq object
#'
#' @param taxobj      A \code{\link{LorMe}} object (usually generated by \code{tax_summary}).
#' @param use_reads   Logical. \code{FALSE} (default) uses **relative abundance** (\code{Base_percent}); \code{TRUE} uses **raw counts**
#'   (\code{Base}).
#'
#' @return A \code{\link[phyloseq:phyloseq]{phyloseq}} object  containing
#'   \code{otu_table}, \code{sample_data}, \code{tax_table} and optionally
#'   \code{phy_tree} (only if \code{taxobj} has a tree).
#' @export
#'
#' @examples
#' \dontrun{
#' data("Two_group")
#'
#' Two_group_phylo=Trans_to_phylo(taxobj = Two_group,use_reads = F)
#'
#' plot_bar(Two_group_phylo,fill="Phylum") #Just to show it can be used for analysis
#' }
Trans_to_phylo <- function(taxobj, use_reads = TRUE) {
  if (!requireNamespace("phyloseq", quietly = TRUE))
    stop("phyloseq required: install.packages('phyloseq')")
  #extraction
  meta     <- methods::slot(taxobj, "groupfile")
  data_lst <- methods::slot(taxobj, "data")
  tree     <- methods::slot(taxobj, "tree")

  ## select relative abundance
  base_key <- if (use_reads==TRUE) "Base" else "Base_percent"
  if (is.null(data_lst[[base_key]]))
    stop(sprintf("'%s' not found in taxobj", base_key))

  otu_df <- data_lst[[base_key]]
  tax_df <- data_lst$Base_taxonomy

  ## build phyloseq compartments
  otu_mat <- as.matrix(otu_df[, -1])
  rownames(otu_mat) <- otu_df$ID

  tax_mat <- as.matrix(tax_df[, -1])
  rownames(tax_mat) <- tax_df$ID

  meta_df <- as.data.frame(meta)
  rownames(meta_df) <- colnames(otu_mat)

  ## encapsulation
  components <- list(
    phyloseq::otu_table(otu_mat, taxa_are_rows = TRUE),
    phyloseq::sample_data(meta_df),
    phyloseq::tax_table(tax_mat)
  )

  ## add tree
  if (!is.null(tree)) {
    components <- c(components, list(phyloseq::phy_tree(tree)))
  }

  #return
  do.call(phyloseq::phyloseq, components)
}

Try the LorMe package in your browser

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

LorMe documentation built on Jan. 12, 2026, 9:06 a.m.