R/micro_PERMANOVA.R

Defines functions micro_PERMANOVA adonis_formula

Documented in micro_PERMANOVA

#' @title A function to run PERMANOVA on tidi_micro data sets
#' @name micro_PERMANOVA
#' @description A wrapper function to call \code{\link[vegan]{adonis2}} from the \code{vegan} package. PERMANOVA is a method for partitioning distance matrices among sources of variation and fitting linear models (e.g., factors, polynomial regression) to distance matrices; uses a permutation test with pseudo-F ratios
#' @param beta_div A dissimilarity matrix calculated by \code{beta_div}
#' @param micro_set A tidy_micro data set
#' @param method A character string indicating the method used to calculated dissimilarity
#' @param ... Covariates of interest
#' @param nperm Number of permutations
#' @param seed Random seed to use for test. This is highly recommended for reproducibility
#' @details The function adonis2 is based on the principles of McArdle & Anderson (2001) and can perform sequential, marginal and overall tests. Function adonis2 also allows using additive constants or squareroot of dissimilarities to avoid negative eigenvalues
#' @references \code{\link{help(vegdist)}} \code{\link{help(adonis2)}}
#' @seealso \code{\link{adonis}}
#' @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")
#'
#' bray \%>\% tidi_adonis(set, method = "bray", bpd1, seed = 234)
#' @export
micro_PERMANOVA <- function(beta_div, micro_set, method, ..., nperm = 999, seed = NULL){
  micro_set %<>%
    dplyr::filter(Lib %in% rownames(beta_div)) %>%
    dplyr::distinct(Lib, .keep_all = T) %>%
    dplyr::arrange(Lib)

  f <- paste("beta_div ~", suppressWarnings(adonis_formula(!!!rlang::quos(...)))) %>%
    as.formula

  set.seed(seed)
  vegan::adonis2(f, data = micro_set, method = method, permutations = nperm)
}

## Function for making adonis formula from "..." in functions
adonis_formula <- function(...){
  rlang::quos(...) %>%           ## Making "..." a quosure
    rlang::splice() %>%            ## Splicing quosure
    unlist %>%            ## Unlisting
    stringr::str_flatten(collapse = " + ") %>%            ## Combining elements of list with "+"
    stringr::str_replace_all(pattern = "~", replacement = "") %>%     ## Removing "~" (why is it there?)
    #  paste("beta_div", ., sep = "~") %>%
    # as.formula %>%
    return()
}
CharlieCarpenter/tidy.micro documentation built on Jan. 19, 2020, 6:28 p.m.