R/Beta_Divs.R

Defines functions beta_div

Documented in beta_div

#' @title Beta Diversity Calculations for tidy_micro
#' @name beta_div
#' @description Calculate beta diversities of your tidy_micro set. This function reformats the data into the original OTU table and then feeds that into the vegdist function
#' @param micro_set A tidy_micro data set
#' @param table Table you'd like to use when calculating alpha diversity. Your lowest level is recommended
#' @param method A dissimilarity method compatible with \code{\link[vegan]{vegdist}}
#' @references \code{\link{help(vegdist)}}
#' @return A symmetrix distance matrix
#' @examples
#' data(phy); data(cla); data(ord); data(fam); data(met)
#'
#' otu_tabs = list(Phylum = phy, Class = cla, Order = ord, Family = fam)
#' set <- tidy_micro(otu_tabs = otu_tabs, meta = met) %>%
#' filter(day == 7) ## Only including the first week
#'
#' ## Bray-Curtis beta diversity
#' bray <- set %>% beta_div(table = "Family")
#'
#' ## Morisita-Horn beta diversity
#' horn <- set %>% beta_div(table = "Family", method = "horn")
#' @export
beta_div <- function(micro_set, table, method = "bray"){

  if(table %nin% unique(micro_set$Table)) stop("Specified table is not in supplied micro_set")

  ## Getting original OTU table
  beta_div <- micro_set %>%
    dplyr::filter(Table == table) %>%
    dplyr::select(cts, Lib, Taxa) %>%
    tidyr::spread(Taxa, cts)

  ## Storing Library names
  Lib <- beta_div$Lib

  ## Calculating Beta divs
  beta_div %<>%
    dplyr::select(-Lib) %>%
    vegan::vegdist(method = method) %>%
    as.matrix

  ## restoring rownames
  rownames(beta_div) <- Lib

  beta_div
}
CharlieCarpenter/tidy.micro documentation built on Jan. 19, 2020, 6:28 p.m.