diff --git a/DESCRIPTION b/DESCRIPTION index 56d6fb8..882685a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -24,8 +24,11 @@ Imports: dplyr, effsize, limma, + lmerTest, logistf, + MASS, permute, + reformulas, rlang, rms, rstatix, @@ -35,7 +38,11 @@ Imports: vegan Suggests: mia, + miaTime, + MatrixGenerics, + nlme, BiocStyle, + DiagrammeR, knitr, rmarkdown, testthat diff --git a/NAMESPACE b/NAMESPACE index 5b72921..ec3f521 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,16 +1,26 @@ # Generated by roxygen2: do not edit by hand export(getAnova) +export(getChisqTest) export(getCorrelationTest) +export(getDunnTest) export(getEffectSize) export(getFirth) +export(getFisherTest) +export(getFriedmanTest) +export(getGlm) export(getKruskal) +export(getLeveneTest) export(getLimma) export(getLm) export(getOrm) export(getPermanova) +export(getPermdisp) +export(getShapiroTest) export(getTTest) +export(getTukeyTest) export(getWilcoxonTest) +importFrom(MASS,glm.nb) importFrom(SummarizedExperiment, assay, assayNames, @@ -37,11 +47,13 @@ importFrom(limma, eBayes, lmFit ) +importFrom(lmerTest,lmer) importFrom(logistf, logistf, logistf.control ) importFrom(permute,how) +importFrom(reformulas,findbars) importFrom(rlang, "!!", .data, @@ -51,27 +63,40 @@ importFrom(rms,orm) importFrom(rstatix, adjust_pvalue, anova_test, + chisq_test, cor_test, + dunn_test, + fisher_test, + friedman_test, kruskal_test, + levene_test, + shapiro_test, t_test, + tukey_hsd, wilcox_test ) importFrom(stats, as.formula, + complete.cases, delete.response, + glm, lm, - lm.fit, model.matrix, na.omit, p.adjust, pchisq, + poisson, reformulate, + residuals, terms, + update, var ) importFrom(tidyr,pivot_longer) importFrom(utils,combn) importFrom(vegan, adonis2, + betadisper, + permutest, vegdist ) diff --git a/R/getChisqTest.R b/R/getChisqTest.R new file mode 100644 index 0000000..e089948 --- /dev/null +++ b/R/getChisqTest.R @@ -0,0 +1,42 @@ +#' @title Perform chi-square test +#' +#' @description +#' Performs chi-square test to compare the prevalence (presence or absence) of +#' features between groups. +#' +#' @details +#' A feature is present in a sample if its value is higher than +#' \code{detection}. The test is performed separately for each feature using the +#' table of groups and presence. Features that are present in all samples or +#' absent in all samples are skipped. P-values are adjusted for the number of +#' features and added to column \code{p.adj}. The chi-square approximation can +#' be inaccurate if there are few samples; use \code{\link{getFisherTest}} then. +#' +#' @param tse A \code{SummarizedExperiment} object. +#' @param formula A formula where the LHS specifies the variable to test +#' (assay name, colData, or rowData variable) and the RHS specifies the +#' grouping variable, e.g., \code{counts ~ Group}. +#' @param detection \code{Numeric scalar}. Values above this threshold are +#' considered present. (Default: \code{0}) +#' @param p.adjust.method \code{Character scalar}. Method passed to +#' \code{p.adjust} for multiple testing correction. (Default: \code{"BH"}) +#' @param ... Additional arguments passed to \code{chisq_test}. +#' +#' @return A \code{data.frame} with test results. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' res <- getChisqTest(tse, counts ~ Geographical_location) +#' +#' @seealso \code{\link{getFisherTest}} +#' +#' @importFrom rstatix chisq_test +#' @export +getChisqTest <- function(tse, formula, detection = 0, p.adjust.method = "BH", ...) { + .calculate_contingency_test( + tse, formula, detection, p.adjust.method, + FUN = chisq_test, ... + ) +} diff --git a/R/getCorrelationTest.R b/R/getCorrelationTest.R index ade00d1..5d6d372 100644 --- a/R/getCorrelationTest.R +++ b/R/getCorrelationTest.R @@ -11,11 +11,19 @@ #' at least three samples remain and both variables vary. P-values are adjusted #' for the number of features and added to column \code{p.adj}. #' -#' If \code{adjust.by} is given, the effect of the covariates is removed first: -#' both variables are regressed on the covariates with a linear model, and the -#' correlation is calculated between the residuals. The p-values are from -#' \code{cor_test} on the residuals, so they do not account for the degrees of -#' freedom used by the covariates and are slightly optimistic. +#' If \code{adjust.by} is given, the effect of the covariates is removed +#' first. For Spearman correlation, both variables are ranked within each +#' feature before this, so the result is the partial Spearman correlation, i.e., +#' the Pearson correlation of the ranks after adjustment. Both variables are +#' regressed on the covariates, and the correlation is calculated between the +#' residuals. A linear model is used, or a linear mixed model if +#' \code{adjust.by} is a formula with random effects, e.g., +#' \code{~ Gender + (1 | Subject)}. Then the residuals are what is left after +#' removing both the fixed and random effects, which is useful for repeated +#' measurements. The p-values are from \code{cor_test} on the residuals, so they +#' do not account for the degrees of freedom used by the covariates and are +#' slightly optimistic. Kendall correlation is not supported with +#' \code{adjust.by}. #' #' @param tse A \code{SummarizedExperiment} object. #' @param formula A formula where the LHS specifies the variable to test @@ -24,9 +32,11 @@ #' @param method \code{Character scalar}. Correlation coefficient, #' \code{"spearman"}, \code{"pearson"} or \code{"kendall"}. #' (Default: \code{"spearman"}) -#' @param adjust.by \code{Character vector} or \code{NULL}. Names of -#' \code{colData} variables whose effect is removed before calculating the -#' correlation. (Default: \code{NULL}) +#' @param adjust.by \code{Character vector}, \code{formula} or \code{NULL}. +#' Names of \code{colData} variables whose effect is removed before +#' calculating the correlation. A formula without the LHS, e.g., +#' \code{~ Gender + (1 | Subject)}, can include random effects. +#' (Default: \code{NULL}) #' @param p.adjust.method \code{Character scalar}. Method passed to #' \code{p.adjust} for multiple testing correction. (Default: \code{"BH"}) #' @param ... Additional arguments passed to \code{cor_test}. @@ -43,10 +53,6 @@ #' # Correlation after removing the effect of covariates #' res <- getCorrelationTest(tse, counts ~ shannon, adjust.by = "Gender") #' -#' @importFrom rstatix cor_test adjust_pvalue -#' @importFrom rlang .data -#' @importFrom dplyr group_by filter ungroup n -#' @importFrom stats var #' @export getCorrelationTest <- function(tse, formula, method = c("spearman", "pearson", "kendall"), adjust.by = NULL, p.adjust.method = "BH", ...) { @@ -56,21 +62,43 @@ getCorrelationTest <- function(tse, formula, method = c("spearman", "pearson", " ) } method <- match.arg(method) + if (!is.null(adjust.by)) { + if (method == "kendall") { + stop("Kendall correlation is not supported with 'adjust.by'.", + call. = FALSE + ) + } + res <- .get_adjusted_correlation( + tse, formula, method, adjust.by, p.adjust.method, ... + ) + } else { + res <- .get_unadjusted_correlation( + tse, formula, method, p.adjust.method, ... + ) + } + return(res) +} + +#' Calculate correlation without adjusting for covariates +#' +#' The data are fetched in long format, and the correlation is calculated for +#' all features with \code{cor_test}. +#' +#' @keywords internal +#' @noRd +#' @importFrom rstatix cor_test adjust_pvalue +#' @importFrom rlang .data +#' @importFrom dplyr group_by filter n +#' @importFrom stats var complete.cases +.get_unadjusted_correlation <- function(tse, formula, method, p.adjust.method, ...) { lhs <- .get_lhs(formula) rhs <- .get_rhs(formula) - # Covariates are fetched in the same way as pairing variables - df <- .get_long_data(tse, formula, adjust.by) + df <- .get_long_data(tse, formula) if (!is.numeric(df[[rhs]])) { stop("The independent variable must be numeric.", call. = FALSE) } - # Only samples with values for all variables can be used - df <- df[stats::complete.cases(df[, c(lhs, rhs, adjust.by)]), , - drop = FALSE - ] - # Remove the effect of covariates from both variables - if (!is.null(adjust.by)) { - df <- .adjust_for_covariates(df, lhs, rhs, adjust.by) - } + # Only samples with values for both variables can be used + df <- df[complete.cases(df[, c(lhs, rhs)]), , drop = FALSE] # Feature filtering: there must be enough samples and variance in both # variables, otherwise the correlation cannot be calculated df <- df |> @@ -85,24 +113,110 @@ getCorrelationTest <- function(tse, formula, method = c("spearman", "pearson", " return(res) } -#' Replace values by residuals after regressing out covariates +#' Calculate correlation after adjusting for covariates #' -#' Within each feature, both the tested variable and the numeric variable are -#' regressed on the covariates with a linear model. +#' The data are fetched in wide format, and the correlation is calculated per +#' feature with \code{.run_adjusted_correlation}. #' #' @keywords internal #' @noRd -#' @importFrom stats lm.fit model.matrix reformulate -.adjust_for_covariates <- function(df, lhs, rhs, adjust.by) { - df <- lapply(split(df, df[["rownames"]]), function(feature_data) { - design_matrix <- model.matrix(reformulate(adjust.by), feature_data) - for (variable in c(lhs, rhs)) { - fit <- lm.fit(design_matrix, feature_data[[variable]]) - feature_data[[variable]] <- fit[["residuals"]] - } - feature_data - }) - df <- do.call(rbind, df) - rownames(df) <- NULL - return(df) +#' @importFrom rstatix adjust_pvalue +#' @importFrom stats reformulate +#' @importFrom SummarizedExperiment colData +.get_adjusted_correlation <- function(tse, formula, method, adjust.by, p.adjust.method, ...) { + # Covariates are given as names or as a formula, e.g., ~ Gender + (1 | ID) + adjust_formula <- if (inherits(adjust.by, "formula")) { + adjust.by + } else { + reformulate(adjust.by) + } + adjust_variables <- all.vars(adjust_formula) + if (!all(adjust_variables %in% colnames(colData(tse)))) { + stop("Covariate(s) not found in colData(x): ", + paste0("'", setdiff(adjust_variables, colnames(colData(tse))), + "'", + collapse = ", " + ), + call. = FALSE + ) + } + # Covariates are sample variables, fetched in the same way as pair.by + data_list <- .get_wide_data(tse, formula, adjust_variables) + if (!is.numeric(data_list[["sample_metadata"]][[.get_rhs(formula)]])) { + stop("The independent variable must be numeric.", call. = FALSE) + } + res <- .train_model_per_feature( + formula = formula, + mat = data_list[["matrix"]], + metadata = data_list[["sample_metadata"]], + FUN = .run_adjusted_correlation, + p_adjust_method = NULL, + method = method, + adjust_formula = adjust_formula, + ... + ) |> as.data.frame() + # Correct for the number of features + res <- adjust_pvalue(res, p.col = "p", method = p.adjust.method) + return(res) +} + +#' Calculate correlation of one feature after adjusting for covariates +#' +#' @param abundance A numeric vector with a value for each sample. +#' @param metadata A \code{data.frame} of sample variables with the numeric +#' variable and the covariates. +#' @param formula The formula, e.g., \code{counts ~ score}. +#' @param method \code{"spearman"} or \code{"pearson"}. +#' @param adjust_formula Formula of the covariates, with or without random +#' effects. +#' @param ... Additional arguments passed to \code{cor_test}. +#' +#' @return A \code{data.frame} with the correlation, or \code{NULL} if it +#' cannot be calculated. +#' +#' @keywords internal +#' @noRd +#' @importFrom rstatix cor_test +#' @importFrom stats lm residuals update var complete.cases as.formula +#' @importFrom reformulas findbars +#' @importFrom lmerTest lmer +.run_adjusted_correlation <- function(abundance, metadata, formula, method, adjust_formula, ...) { + lhs <- .get_lhs(formula) + rhs <- .get_rhs(formula) + # The tested variable (.y) and the numeric variable (.x) have fixed names + # so that they cannot clash with the names of the covariates + df <- cbind.data.frame(metadata, .y = abundance) + df[[".x"]] <- df[[rhs]] + # Only samples with values for all variables can be used + df <- df[complete.cases(df[, c(".y", ".x", all.vars(adjust_formula))]), , + drop = FALSE + ] + if (nrow(df) < 3L) { + return(NULL) + } + # Partial Spearman correlation is the Pearson correlation of the ranks + if (method == "spearman") { + df[[".y"]] <- rank(df[[".y"]]) + df[[".x"]] <- rank(df[[".x"]]) + } + # Random effects, e.g., (1 | Subject), require a mixed model + fit_function <- if (is.null(findbars(adjust_formula))) lm else lmer + # Replace both variables by their residuals, i.e., remove the covariates + for (variable in c(".y", ".x")) { + df[[variable]] <- fit_function( + update(adjust_formula, as.formula(paste(variable, "~ ."))), + data = df + ) |> + residuals() |> + unname() + } + # The correlation cannot be calculated without variance + if (var(df[[".y"]]) == 0 || var(df[[".x"]]) == 0) { + return(NULL) + } + # Ranks were already taken, so Pearson is used for Spearman as well + res <- cor_test(df, vars = ".y", vars2 = ".x", method = "pearson", ...) + res[["var1"]] <- lhs + res[["var2"]] <- rhs + return(res) } diff --git a/R/getDunnTest.R b/R/getDunnTest.R new file mode 100644 index 0000000..af548a8 --- /dev/null +++ b/R/getDunnTest.R @@ -0,0 +1,37 @@ +#' @title Perform Dunn's post-hoc test +#' +#' @description +#' Performs Dunn's test to compare all pairs of groups after Kruskal-Wallis +#' test. +#' +#' @param tse A \code{SummarizedExperiment} object. +#' @param formula A formula where the LHS specifies the variable to test +#' (assay name, colData, or rowData variable) and the RHS specifies the +#' grouping variable, e.g., \code{counts ~ Group}. +#' @param ... Additional arguments passed to \code{dunn_test}. +#' +#' @return A \code{data.frame} with test results. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' res <- getDunnTest(tse, counts ~ Geographical_location) +#' +#' @seealso \code{\link{getKruskal}} +#' +#' @importFrom rstatix dunn_test +#' @export +getDunnTest <- function(tse, formula, ...) { + if (length(all.vars(formula[[3]])) != 1L) { + stop("Formula RHS must specify exactly one grouping variable.", + call. = FALSE + ) + } + df <- .get_long_data(tse, formula) + res <- .calculate_rstatix( + df = df, formula = formula, + FUN = dunn_test, ... + ) + return(res) +} diff --git a/R/getEffectSize.R b/R/getEffectSize.R index 5928378..4fa8529 100644 --- a/R/getEffectSize.R +++ b/R/getEffectSize.R @@ -1,15 +1,26 @@ #' @title Calculate effect sizes between groups #' #' @description -#' Calculates effect sizes between each pair of groups with Cliff's delta or -#' Cohen's d. +#' Calculates effect sizes between each pair of groups: the difference, ratio +#' or log ratio of means, or standardized effect sizes (Cliff's delta or +#' Cohen's d). #' #' @details +#' The difference (\code{"difference"}), ratio (\code{"ratio"}) and log2 ratio +#' (\code{"log_ratio"}) are calculated from the means of the groups, i.e., +#' \code{mean(group1) - mean(group2)}, \code{mean(group1) / mean(group2)} and +#' \code{log2(mean(group1) / mean(group2))}. The log ratio is the log2 fold +#' change. Values are used as they are, so the ratios are not defined if the mean +#' of \code{group2} is zero, and the log ratio requires positive means. These +#' effect sizes have no confidence intervals or magnitude. +#' #' Cliff's delta is a non-parametric effect size based on how often values in #' one group are larger than values in the other. Cohen's d is the difference #' in means scaled by the pooled standard deviation. Both are calculated with #' the \code{effsize} package. In paired data, Cohen's d is calculated from -#' the within-pair differences. Paired Cliff's delta is not supported. +#' the within-pair differences. Paired Cliff's delta is not supported. The +#' difference, ratio and log ratio of paired data are calculated from the means +#' of the matched values. #' #' Groups are compared pairwise in the same order as in #' \code{\link{getWilcoxonTest}}. Positive values mean that values are higher @@ -20,12 +31,13 @@ #' (assay name, colData, or rowData variable) and the RHS specifies the #' grouping variable, e.g., \code{counts ~ Group}. #' @param method \code{Character scalar}. Effect size to calculate, -#' \code{"cliff"} or \code{"cohen"}. (Default: \code{"cliff"}) +#' \code{"cliff"}, \code{"cohen"}, \code{"difference"}, \code{"ratio"} or +#' \code{"log_ratio"}. (Default: \code{"cliff"}) #' @param pair.by \code{Character scalar} or \code{NULL}. Column for pairing -#' samples in paired effect sizes (\code{method = "cohen"} only). Only pairs -#' present in both groups are used. (Default: \code{NULL}) +#' samples in paired effect sizes (not supported for \code{"cliff"}). Only +#' pairs present in both groups are used. (Default: \code{NULL}) #' @param ... Additional arguments passed to \code{effsize::cliff.delta} or -#' \code{effsize::cohen.d}. +#' \code{effsize::cohen.d}. Not used by the other methods. #' #' @return A \code{data.frame} with one row per feature and pair of groups, #' and columns \code{rownames}, \code{group1}, \code{group2}, @@ -37,12 +49,19 @@ #' tse <- mia::agglomerateByRank(tse, "phylum") #' res <- getEffectSize(tse, counts ~ Geographical_location) #' +#' # Log2 fold change +#' res <- getEffectSize( +#' tse, counts ~ Geographical_location, +#' method = "log_ratio" +#' ) +#' #' @seealso #' \code{\link[effsize:cliff.delta]{effsize::cliff.delta}}, #' \code{\link[effsize:cohen.d]{effsize::cohen.d}} #' #' @export -getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), +getEffectSize <- function(tse, formula, + method = c("cliff", "cohen", "difference", "ratio", "log_ratio"), pair.by = NULL, ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", @@ -97,7 +116,10 @@ getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), # effsize function used for the comparison effect_size_function <- switch(method, cliff = cliff.delta, - cohen = cohen.d + cohen = cohen.d, + difference = .calculate_difference, + ratio = .calculate_ratio, + log_ratio = .calculate_log_ratio ) values <- .get_pair_values( feature_data, group_pair, response_name, group_column, pair.by @@ -176,3 +198,42 @@ getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), second = second_values |> na.omit() ) } + +#' Difference, ratio and log2 ratio of the means of two groups +#' +#' Return the same structure as the effsize functions: an estimate, a +#' confidence interval and a magnitude, which are not available here. For +#' paired data, the values are already matched, and the difference of the means +#' equals the mean of the differences. +#' +#' @param x,y \code{Numeric vector}. Values of the first and second group. +#' @param ... Not used. Allows the same call as for the effsize functions. +#' +#' @keywords internal +#' @noRd +.calculate_difference <- function(x, y, ...) { + .create_effect_size(mean(x) - mean(y)) +} + +#' @keywords internal +#' @noRd +.calculate_ratio <- function(x, y, ...) { + .create_effect_size(mean(x) / mean(y)) +} + +#' @keywords internal +#' @noRd +.calculate_log_ratio <- function(x, y, ...) { + .create_effect_size(log2(mean(x) / mean(y))) +} + +#' Effect size without confidence interval and magnitude +#' +#' @keywords internal +#' @noRd +.create_effect_size <- function(estimate) { + list( + estimate = estimate, conf.int = c(NA_real_, NA_real_), + magnitude = NA_character_ + ) +} diff --git a/R/getFisherTest.R b/R/getFisherTest.R new file mode 100644 index 0000000..ad60b7f --- /dev/null +++ b/R/getFisherTest.R @@ -0,0 +1,41 @@ +#' @title Perform Fisher's exact test +#' +#' @description +#' Performs Fisher's exact test to compare the prevalence (presence or absence) +#' of features between groups. +#' +#' @details +#' A feature is present in a sample if its value is higher than +#' \code{detection}. The test is performed separately for each feature using the +#' table of groups and presence. Features that are present in all samples or +#' absent in all samples are skipped. P-values are adjusted for the number of +#' features and added to column \code{p.adj}. +#' +#' @param tse A \code{SummarizedExperiment} object. +#' @param formula A formula where the LHS specifies the variable to test +#' (assay name, colData, or rowData variable) and the RHS specifies the +#' grouping variable, e.g., \code{counts ~ Group}. +#' @param detection \code{Numeric scalar}. Values above this threshold are +#' considered present. (Default: \code{0}) +#' @param p.adjust.method \code{Character scalar}. Method passed to +#' \code{p.adjust} for multiple testing correction. (Default: \code{"BH"}) +#' @param ... Additional arguments passed to \code{fisher_test}. +#' +#' @return A \code{data.frame} with test results. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' res <- getFisherTest(tse, counts ~ Geographical_location) +#' +#' @seealso \code{\link{getChisqTest}} +#' +#' @importFrom rstatix fisher_test +#' @export +getFisherTest <- function(tse, formula, detection = 0, p.adjust.method = "BH", ...) { + .calculate_contingency_test( + tse, formula, detection, p.adjust.method, + FUN = fisher_test, ... + ) +} diff --git a/R/getFriedmanTest.R b/R/getFriedmanTest.R new file mode 100644 index 0000000..80dfa11 --- /dev/null +++ b/R/getFriedmanTest.R @@ -0,0 +1,75 @@ +#' @title Perform Friedman test +#' +#' @description +#' Performs Friedman test to compare values between two or more paired groups, +#' e.g., repeated measurements from the same subjects. +#' +#' @details +#' The test is performed separately for each feature. Only pairing IDs present +#' in all groups of the feature are used. +#' +#' @param tse A \code{SummarizedExperiment} object. +#' @param formula A formula where the LHS specifies the variable to test +#' (assay name, colData, or rowData variable) and the RHS specifies the +#' grouping variable, e.g., \code{counts ~ Time}. +#' @param pair.by \code{Character scalar}. Column for pairing samples. +#' @param ... Additional arguments passed to \code{friedman_test}. +#' +#' @return A \code{data.frame} with test results. +#' +#' @examples +#' # Subjects measured at three timepoints +#' data(Kumaraswamy2024, package = "miaTime") +#' tse <- Kumaraswamy2024 +#' tse$timepoint <- factor(tse$timepoint) +#' res <- getFriedmanTest(tse, signal ~ timepoint, pair.by = "subject") +#' +#' @export +getFriedmanTest <- function(tse, formula, pair.by, ...) { + if (length(all.vars(formula[[3]])) != 1L) { + stop("Formula RHS must specify exactly one grouping variable.", + call. = FALSE + ) + } + lhs <- .get_lhs(formula) + rhs <- .get_rhs(formula) + df <- .get_long_data(tse, formula, pair.by) |> + .get_complete_blocks(lhs, rhs, pair.by) + .calculate_friedman(df, lhs, rhs, pair.by, ...) +} + +#' Keep only complete blocks +#' +#' Friedman test needs complete blocks, i.e., each pairing ID must be present +#' in all groups of the feature. +#' +#' @return Long-format data grouped by feature. +#' +#' @keywords internal +#' @noRd +#' @importFrom rlang .data +#' @importFrom dplyr group_by filter mutate n_distinct +.get_complete_blocks <- function(df, lhs, rhs, pair.by) { + df |> + filter(!is.na(.data[[lhs]])) |> + # Number of groups of each feature + group_by(.data[["rownames"]]) |> + mutate(n_groups = n_distinct(.data[[rhs]])) |> + # Pairing IDs found in all groups of the feature + group_by(.data[["rownames"]], .data[[pair.by]]) |> + filter(n_distinct(.data[[rhs]]) == .data[["n_groups"]]) |> + group_by(.data[["rownames"]]) +} + +#' Run Friedman test for each feature +#' +#' @return A \code{data.frame} with test results. +#' +#' @keywords internal +#' @noRd +#' @importFrom rstatix friedman_test +.calculate_friedman <- function(df, lhs, rhs, pair.by, ...) { + # Pairing variable is given after the bar in the formula + friedman_formula <- paste(lhs, "~", rhs, "|", pair.by) |> as.formula() + friedman_test(df, friedman_formula, ...) +} diff --git a/R/getGlm.R b/R/getGlm.R new file mode 100644 index 0000000..1fbce2a --- /dev/null +++ b/R/getGlm.R @@ -0,0 +1,145 @@ +#' @title Fit generalized linear model per feature +#' +#' @description +#' Fits a generalized linear model (GLM) per feature. The distribution +#' (likelihood) of the abundances is chosen +#' with \code{family}, e.g., Poisson or negative binomial for counts, binomial +#' for presence, or Gamma for positive continuous values. +#' +#' @details +#' The model is fitted with \code{\link[stats]{glm}}. The \code{family} +#' argument is a family object, e.g., \code{poisson()}, \code{quasipoisson()}, +#' \code{binomial()}, \code{Gamma(link = "log")} or \code{gaussian()}. Use +#' \code{family = "negbin"} for a negative binomial model fitted with +#' \code{\link[MASS]{glm.nb}}, which estimates the dispersion of each feature. +#' +#' An offset can be given with \code{offset}, e.g., the log of the library size +#' of each sample for a Poisson or negative binomial model, so that the model +#' is for the abundance relative to the library size. The offset is added to +#' the linear predictor as such, so it must be on the scale of the link +#' function. +#' +#' The estimates are on the scale of the link function, e.g., the log +#' scale for a Poisson or negative binomial model, and the log odds for a +#' binomial model. The \code{gaussian()} family gives the same result as +#' \code{\link{getLm}}. +#' +#' @param tse A \code{SummarizedExperiment} object. +#' @param formula A formula where the LHS specifies the assay or colData +#' variable and the RHS specifies variables from \code{colData(tse)}, +#' e.g., \code{counts ~ Group}. +#' @param family A family object or \code{"negbin"}. (Default: +#' \code{poisson()}) +#' @param offset \code{Character scalar}, \code{numeric vector} or \code{NULL}. +#' Offset of the model. Either the name of a numeric column in +#' \code{colData(tse)} or a vector with a value for each sample. If +#' \code{NULL}, no offset is used. (Default: \code{NULL}) +#' @param p_adjust_method \code{Character scalar} or \code{NULL}. Method passed +#' to \code{p.adjust} for multiple testing correction. If \code{NULL}, no +#' adjusted p-values are added. (Default: \code{"BH"}) +#' @param ... Additional arguments passed to \code{glm} (or \code{glm.nb}). +#' +#' @return A \code{data.frame} with per-feature model coefficients, p-values, +#' and optionally adjusted p-values in column \code{q_value}. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' +#' # Poisson model for counts +#' res <- getGlm(tse, counts ~ Geographical_location) +#' +#' # Negative binomial model for overdispersed counts +#' res <- getGlm(tse, counts ~ Geographical_location, family = "negbin") +#' +#' # Offset: the log of the library size of each sample +#' tse$log_total <- log(colSums(SummarizedExperiment::assay(tse, "counts"))) +#' res <- getGlm(tse, counts ~ Geographical_location, offset = "log_total") +#' +#' # Binomial model (logistic regression) for presence +#' tse <- mia::transformAssay(tse, method = "pa") +#' res <- getGlm(tse, pa ~ Geographical_location, family = binomial()) +#' +#' @seealso \code{\link{getLm}}, \code{\link{getFirth}} +#' +#' @importFrom stats poisson +#' @export +getGlm <- function(tse, formula, family = poisson(), offset = NULL, + p_adjust_method = "BH", ...) { + data_list <- .get_wide_data(tse, formula) + offset_values <- .get_offset(tse, offset) + res <- .train_model_per_feature( + formula = formula, + mat = data_list[["matrix"]], + metadata = data_list[["sample_metadata"]], + FUN = function(abundance, metadata, formula) { + .run_glm( + abundance, metadata, formula, family, offset_values, ... + ) + }, + p_adjust_method = p_adjust_method + ) + return(res) +} + +#' Get offset values for each sample +#' +#' @return A numeric vector with a value for each sample, or \code{NULL}. +#' +#' @keywords internal +#' @noRd +#' @importFrom SummarizedExperiment colData +.get_offset <- function(tse, offset) { + if (is.null(offset)) { + return(NULL) + } + # Name of a column in colData + if (is.character(offset) && length(offset) == 1L) { + if (!offset %in% colnames(colData(tse))) { + stop("'offset' must be a column in colData(x).", call. = FALSE) + } + offset <- colData(tse)[[offset]] + } + if (!is.numeric(offset) || length(offset) != ncol(tse) || + anyNA(offset)) { + stop("'offset' must be a numeric vector without missing values and ", + "with a value for each sample.", + call. = FALSE + ) + } + return(offset) +} + +#' @keywords internal +#' @noRd +#' @importFrom stats glm +#' @importFrom MASS glm.nb +#' @importFrom broom tidy +.run_glm <- function(abundance, metadata, formula, family, offset_values, ...) { + mm <- .create_design_matrix(formula, metadata) + mm <- cbind.data.frame(mm, abundance = abundance) + + # The offset is a term of the formula so that it works in glm and glm.nb + model_formula <- if (is.null(offset_values)) { + abundance ~ . + } else { + abundance ~ . + offset(offset_values) + } + # Negative binomial model has its own fitting function + if (identical(family, "negbin")) { + fit <- glm.nb(model_formula, data = mm, ...) + } else { + fit <- glm(model_formula, family = family, data = mm, ...) + } + res <- tidy(fit) + # Names of the values are not needed + res <- data.frame( + variable = res[["term"]], + estimate = unname(res[["estimate"]]), + p_value = unname(res[["p.value"]]) + ) + res <- res[res$variable != "(Intercept)", , drop = FALSE] + rownames(res) <- NULL + return(res) +} diff --git a/R/getLeveneTest.R b/R/getLeveneTest.R new file mode 100644 index 0000000..0dfdc6b --- /dev/null +++ b/R/getLeveneTest.R @@ -0,0 +1,37 @@ +#' @title Perform Levene's test +#' +#' @description +#' Performs Levene's test to check whether the variances are equal between +#' groups. +#' +#' @param tse A \code{SummarizedExperiment} object. +#' @param formula A formula where the LHS specifies the variable to test +#' (assay name, colData, or rowData variable) and the RHS specifies the +#' grouping variable, e.g., \code{counts ~ Group}. +#' @param ... Additional arguments passed to \code{levene_test}. +#' +#' @return A \code{data.frame} with test results. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' res <- getLeveneTest(tse, counts ~ Geographical_location) +#' +#' @importFrom rstatix levene_test +#' @export +getLeveneTest <- function(tse, formula, ...) { + if (length(all.vars(formula[[3]])) != 1L) { + stop("Formula RHS must specify exactly one grouping variable.", + call. = FALSE + ) + } + df <- .get_long_data(tse, formula) + # Levene's test requires a factor + df[[.get_rhs(formula)]] <- factor(df[[.get_rhs(formula)]]) + res <- .calculate_rstatix( + df = df, formula = formula, + FUN = levene_test, ... + ) + return(res) +} diff --git a/R/getLm.R b/R/getLm.R index 5188b6b..3eddce6 100644 --- a/R/getLm.R +++ b/R/getLm.R @@ -2,11 +2,20 @@ #' #' @description #' Fits a linear model per feature using wide-format data and sample metadata. +#' Random effects can be added to the formula to fit a linear mixed model, e.g., +#' for repeated measurements from the same subject. +#' +#' @details +#' If the formula has random effects, as in \code{lme4}, e.g., +#' \code{rclr ~ Group + (1 | Subject)}, a linear mixed model is fitted with +#' \code{lmerTest::lmer}, which provides p-values for the fixed effects. +#' Otherwise, a linear model is fitted with \code{lm}. #' #' @param tse A \code{SummarizedExperiment} object. #' @param formula A formula where the LHS specifies the assay or colData #' variable and the RHS specifies variables from \code{colData(tse)}, -#' e.g., \code{rclr ~ Group}. +#' e.g., \code{rclr ~ Group}. Random effects are given as in \code{lme4}, +#' e.g., \code{rclr ~ Group + (1 | Subject)}. #' @param p_adjust_method \code{Character scalar} or \code{NULL}. Method passed #' to \code{p.adjust} for multiple testing correction. If \code{NULL}, no #' adjusted p-values are added. (Default: \code{"BH"}) @@ -22,16 +31,26 @@ #' tse <- mia::transformAssay(tse, method = "rclr") #' res <- getLm(tse, rclr ~ Geographical_location) #' +#' # Mixed model for subjects measured at several timepoints +#' data(Kumaraswamy2024, package = "miaTime") +#' tse <- Kumaraswamy2024[1:10, ] +#' tse$timepoint <- factor(tse$timepoint) +#' tse <- mia::transformAssay(tse, assay.type = "signal", method = "rclr") +#' res <- getLm(tse, rclr ~ timepoint + (1 | subject)) +#' #' @importFrom broom tidy #' @importFrom stats lm +#' @importFrom reformulas findbars #' @export getLm <- function(tse, formula, p_adjust_method = "BH", ...) { data_list <- .get_wide_data(tse, formula) + # Random effects, e.g., (1 | Subject), require a mixed model + FUN <- if (is.null(findbars(formula))) .run_lm else .run_lmm res <- .train_model_per_feature( formula = formula, mat = data_list[["matrix"]], metadata = data_list[["sample_metadata"]], - FUN = .run_lm, + FUN = FUN, p_adjust_method = p_adjust_method ) return(res) @@ -53,3 +72,23 @@ getLm <- function(tse, formula, p_adjust_method = "BH", ...) { rownames(res) <- NULL return(res) } + +#' @keywords internal +#' @noRd +#' @importFrom lmerTest lmer +#' @importFrom stats update +.run_lmm <- function(abundance, metadata, formula) { + data_model <- cbind.data.frame(metadata, abundance = abundance) + # The LHS is the abundance of the feature + fit <- lmer(update(formula, abundance ~ .), data = data_model) + res <- summary(fit)[["coefficients"]] |> as.data.frame() + + res <- data.frame( + variable = rownames(res), + estimate = res[["Estimate"]], + p_value = res[["Pr(>|t|)"]] + ) + res <- res[res$variable != "(Intercept)", , drop = FALSE] + rownames(res) <- NULL + return(res) +} diff --git a/R/getPermdisp.R b/R/getPermdisp.R new file mode 100644 index 0000000..ed920ea --- /dev/null +++ b/R/getPermdisp.R @@ -0,0 +1,93 @@ +#' @title Perform test for homogeneity of multivariate dispersions +#' +#' @description +#' Performs PERMDISP to test whether the dispersion (variability) of the +#' composition differs between groups. +#' +#' @details +#' PERMANOVA (\code{\link{getPermanova}}) is also sensitive to differences in +#' dispersion between groups, so PERMDISP is a useful companion test. A +#' distance matrix between samples is calculated from the assay with +#' \code{\link[vegan:vegdist]{vegan::vegdist}}, distances to the group centroids +#' are calculated with +#' \code{\link[vegan:betadisper]{vegan::betadisper}}, and the groups are +#' compared with a permutation test. The p-value is based on permutations, so +#' set a seed for reproducible results. +#' +#' @param tse A \code{SummarizedExperiment} object. +#' @param formula A formula where the LHS specifies the assay name and the RHS +#' specifies the grouping variable from \code{colData}, e.g., +#' \code{counts ~ Group}. +#' @param method \code{Character scalar}. Dissimilarity index passed to +#' \code{vegdist}. (Default: \code{"bray"}) +#' @param permutations \code{Integer scalar}. Number of permutations. +#' (Default: \code{999}) +#' @param ... Additional arguments passed to \code{permutest}. +#' +#' @return A \code{data.frame} with columns \code{n}, \code{Df}, \code{F} and +#' \code{p}. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' set.seed(1) +#' res <- getPermdisp(tse, counts ~ Geographical_location) +#' +#' @seealso \code{\link[vegan:betadisper]{vegan::betadisper}} +#' +#' @export +getPermdisp <- function(tse, formula, method = "bray", permutations = 999L, ...) { + if (length(all.vars(formula[[3]])) != 1L) { + stop("Formula RHS must specify exactly one grouping variable.", + call. = FALSE + ) + } + group_column <- .get_rhs(formula) + # Samples (rows) with a group, and their groups + samples <- .get_permdisp_samples(tse, formula, group_column) + # Distances to group centroids and a permutation test for the difference + .calculate_permdisp( + samples[["abundance"]], samples[["groups"]], method, permutations, ... + ) +} + +#' Get samples and groups for PERMDISP +#' +#' Samples without a group cannot be used. +#' +#' @return A list with the abundance matrix (samples as rows, as required by +#' vegdist) and the groups of the samples. +#' +#' @keywords internal +#' @noRd +.get_permdisp_samples <- function(tse, formula, group_column) { + data_list <- .get_wide_data(tse, formula) + abundance <- data_list[["matrix"]] |> t() + sample_data <- data_list[["sample_metadata"]] + has_values <- stats::complete.cases(sample_data) + sample_data <- sample_data[has_values, , drop = FALSE] + # Check that there are at least two groups + .get_group_names(sample_data, group_column) + list( + abundance = abundance[has_values, , drop = FALSE], + groups = sample_data[[group_column]] + ) +} + +#' Run PERMDISP +#' +#' @return A one-row \code{data.frame}. +#' +#' @keywords internal +#' @noRd +#' @importFrom vegan vegdist betadisper permutest +.calculate_permdisp <- function(abundance, groups, method, permutations, ...) { + fit <- vegdist(abundance, method) |> betadisper(groups) + test <- permutest(fit, permutations = permutations, ...)[["tab"]] + # The first row of the table is the grouping variable + data.frame( + n = length(groups), Df = test[["Df"]][[1L]], F = test[["F"]][[1L]], + p = test[["Pr(>F)"]][[1L]] + ) +} diff --git a/R/getShapiroTest.R b/R/getShapiroTest.R new file mode 100644 index 0000000..bef9961 --- /dev/null +++ b/R/getShapiroTest.R @@ -0,0 +1,83 @@ +#' @title Perform Shapiro-Wilk test on residuals +#' +#' @description +#' Performs Shapiro-Wilk test to check whether the residuals of a model are +#' normally distributed. +#' +#' @details +#' The normality assumption concerns the residuals, not the values. For each +#' feature, a model is fitted as in \code{\link{getLm}}, and its residuals are tested. By default, a linear +#' model \code{variable ~ group} is fitted, and the residuals are the +#' differences from the group means. The formula can have several variables and, +#' as in \code{getLm}, random effects, e.g., \code{counts ~ Group + (1 | Subject)}, +#' which fits a linear mixed model. +#' +#' Features are tested only if they have at least three values and the +#' residuals vary. Features where the model cannot be fitted are skipped with a +#' warning. P-values are adjusted for the number of features and added to column +#' \code{p.adj}. +#' +#' @param tse A \code{SummarizedExperiment} object. +#' @param formula A formula where the LHS specifies the variable to test +#' (assay name or colData variable) and the RHS specifies variables from +#' \code{colData(tse)}, e.g., \code{counts ~ Group}. Random effects are +#' given as in \code{lme4}. +#' @param p.adjust.method \code{Character scalar}. Method passed to +#' \code{p.adjust} for multiple testing correction. (Default: \code{"BH"}) +#' +#' @return A \code{data.frame} with test results. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' res <- getShapiroTest(tse, counts ~ Geographical_location) +#' +#' # Mixed model for subjects measured at several timepoints +#' data(Kumaraswamy2024, package = "miaTime") +#' tse <- Kumaraswamy2024[1:10, ] +#' tse$timepoint <- factor(tse$timepoint) +#' res <- getShapiroTest(tse, signal ~ timepoint + (1 | subject)) +#' +#' @seealso \code{\link{getLeveneTest}}, \code{\link{getLm}} +#' +#' @importFrom rstatix shapiro_test adjust_pvalue +#' @importFrom stats lm residuals var update complete.cases +#' @importFrom lmerTest lmer +#' @importFrom reformulas findbars +#' @export +getShapiroTest <- function(tse, formula, p.adjust.method = "BH") { + data_list <- .get_wide_data(tse, formula) + res <- .train_model_per_feature( + formula = formula, + mat = data_list[["matrix"]], + metadata = data_list[["sample_metadata"]], + FUN = .run_shapiro, + p_adjust_method = NULL + ) |> as.data.frame() + res[["p.adj"]] <- p.adjust(res[["p"]], method = p.adjust.method) + return(res) +} + +#' Test the residuals of the model of a feature +#' +#' @return A \code{data.frame} or \code{NULL} if the feature cannot be tested. +#' +#' @keywords internal +#' @noRd +#' @importFrom stats p.adjust +.run_shapiro <- function(abundance, metadata, formula) { + data_model <- cbind.data.frame(metadata, abundance = abundance) + data_model <- data_model[complete.cases(data_model), , drop = FALSE] + model_formula <- update(formula, abundance ~ .) + + # Random effects, e.g., (1 | Subject), require a mixed model + FUN <- if (is.null(findbars(formula))) lm else lmer + res <- FUN(model_formula, data = data_model) |> residuals() + + # Test needs at least three values that are not all the same + if (length(res) < 3L || isTRUE(var(res) == 0)) { + return(NULL) + } + shapiro_test(data.frame(residual = unname(res)), vars = "residual") +} diff --git a/R/getTukeyTest.R b/R/getTukeyTest.R new file mode 100644 index 0000000..e5fc118 --- /dev/null +++ b/R/getTukeyTest.R @@ -0,0 +1,37 @@ +#' @title Perform Tukey's HSD post-hoc test +#' +#' @description +#' Performs Tukey's honest significant difference test to compare all pairs of +#' groups after ANOVA. +#' +#' @param tse A \code{SummarizedExperiment} object. +#' @param formula A formula where the LHS specifies the variable to test +#' (assay name, colData, or rowData variable) and the RHS specifies the +#' grouping variable, e.g., \code{counts ~ Group}. +#' @param ... Additional arguments passed to \code{tukey_hsd}. +#' +#' @return A \code{data.frame} with test results. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' res <- getTukeyTest(tse, counts ~ Geographical_location) +#' +#' @seealso \code{\link{getAnova}} +#' +#' @importFrom rstatix tukey_hsd +#' @export +getTukeyTest <- function(tse, formula, ...) { + if (length(all.vars(formula[[3]])) != 1L) { + stop("Formula RHS must specify exactly one grouping variable.", + call. = FALSE + ) + } + df <- .get_long_data(tse, formula) + res <- .calculate_rstatix( + df = df, formula = formula, + FUN = tukey_hsd, ... + ) + return(res) +} diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index 44676d1..8261131 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -2,29 +2,25 @@ #' #' @description #' Performs Wilcoxon rank-sum test (Mann-Whitney U) to compare values between -#' two groups. An effect size is added to the results. +#' two groups. #' #' @details #' Without \code{pair.by}, the unpaired Wilcoxon rank-sum test is used. With #' \code{pair.by}, samples are matched and the paired signed-rank test is #' used. If there are more than two groups, all pairs are compared. #' -#' The effect size from \code{\link{getEffectSize}} is added to the results. -#' Paired Cliff's delta is not supported. +#' The test does not calculate an effect size. Use +#' \code{\link{getEffectSize}} as a separate step. #' #' @param tse A \code{SummarizedExperiment} object. #' @param formula A formula where the LHS specifies the variable to test #' (assay name, colData, or rowData variable) and the RHS specifies the #' grouping variable, e.g., \code{counts ~ Group}. -#' @param effect.size \code{Character scalar}. Effect size from -#' \code{\link{getEffectSize}} added to the results, \code{"cliff"} or -#' \code{"cohen"}. Paired Cliff's delta is not supported. (Default: -#' \code{"cliff"}) #' @param pair.by \code{Character scalar} or \code{NULL}. Column for pairing #' samples in paired tests. (Default: \code{NULL}) #' @param ... Additional arguments passed to \code{wilcox_test}. #' -#' @return A \code{data.frame} with test results and effect size. +#' @return A \code{data.frame} with test results. #' #' @examples #' data(peerj13075, package = "mia") @@ -32,17 +28,9 @@ #' tse <- mia::agglomerateByRank(tse, "phylum") #' res <- getWilcoxonTest(tse, counts ~ Geographical_location) #' -#' # Use Cohen's d instead of Cliff's delta -#' res <- getWilcoxonTest( -#' tse, counts ~ Geographical_location, -#' effect.size = "cohen" -#' ) -#' #' @importFrom rstatix wilcox_test -#' @importFrom dplyr left_join #' @export -getWilcoxonTest <- function(tse, formula, effect.size = c("cliff", "cohen"), pair.by = NULL, ...) { - effect.size <- match.arg(effect.size) +getWilcoxonTest <- function(tse, formula, pair.by = NULL, ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE @@ -53,14 +41,5 @@ getWilcoxonTest <- function(tse, formula, effect.size = c("cliff", "cohen"), pai df = df, formula = formula, pair.by = pair.by, FUN = wilcox_test, ... ) - if (!is.null(pair.by) && effect.size == "cliff") { - warning("Paired Cliff's delta is not supported; effect size was ", - "not calculated. Use effect.size = 'cohen' for paired data.", - call. = FALSE - ) - return(res) - } - es <- .calculate_effect_size(df, formula, effect.size, pair.by) - res <- left_join(res, es, by = c("rownames", "group1", "group2")) return(res) } diff --git a/R/utils.R b/R/utils.R index 87e3ff5..a7a9427 100644 --- a/R/utils.R +++ b/R/utils.R @@ -162,6 +162,43 @@ combn(2L, simplify = FALSE) } +################################################################################ +# Contingency table tests +################################################################################ + +#' Test presence/absence between groups for each feature +#' +#' A feature is present in a sample if its value is higher than the detection +#' threshold. The test is run on the table of groups and presence. +#' +#' @keywords internal +#' @noRd +#' @importFrom dplyr bind_rows +#' @importFrom stats p.adjust +.calculate_contingency_test <- function(tse, formula, detection, p.adjust.method, FUN, ...) { + if (length(all.vars(formula[[3]])) != 1L) { + stop("Formula RHS must specify exactly one grouping variable.", + call. = FALSE + ) + } + lhs <- .get_lhs(formula) + rhs <- .get_rhs(formula) + df <- .get_long_data(tse, formula) + df <- df[!is.na(df[[lhs]]) & !is.na(df[[rhs]]), , drop = FALSE] + results <- lapply(split(df, df[["rownames"]]), function(feature_data) { + present <- feature_data[[lhs]] > detection + # Test needs variation in both groups and presence + if (length(unique(present)) < 2L || + length(unique(feature_data[[rhs]])) < 2L) { + return(NULL) + } + FUN(table(feature_data[[rhs]], present), ...) + }) + results <- bind_rows(results, .id = "rownames") |> as.data.frame() + results[["p.adj"]] <- p.adjust(results[["p"]], method = p.adjust.method) + return(results) +} + ################################################################################ # Rstatix calculator ################################################################################ @@ -175,7 +212,7 @@ #' @noRd #' @importFrom rlang sym !! #' @importFrom rlang .data -#' @importFrom dplyr group_by filter ungroup n_distinct arrange +#' @importFrom dplyr group_by filter ungroup n_distinct arrange mutate #' @importFrom stats var .calculate_rstatix <- function(df, formula, FUN, pair.by = NULL, ...) { lhs <- .get_lhs(formula) |> sym() @@ -196,14 +233,23 @@ n_distinct(!!rhs) >= 2 ) - # Paired samples are controlled in rstatix with sorting if (!is.null(pair.by)) { + # Paired tests need each pairing ID in all groups of the feature + df <- df |> + filter(!is.na(!!lhs)) |> + group_by(.data[["rownames"]]) |> + mutate(n_groups = n_distinct(!!rhs)) |> + group_by(.data[["rownames"]], !!sym(pair.by)) |> + filter(n_distinct(!!rhs) == .data[["n_groups"]]) |> + group_by(.data[["rownames"]]) + # Paired samples are controlled in rstatix with sorting df <- df |> arrange(!!sym(pair.by)) } # Create argument list + # Data is passed by position because functions name it differently args <- list( - data = df, + df, formula = formula ) if (!is.null(pair.by)) { @@ -285,14 +331,32 @@ #' @importFrom rlang .data #' @importFrom stats p.adjust .train_model_per_feature <- function(formula, mat, metadata, FUN, - p_adjust_method = "BH") { + p_adjust_method = "BH", ...) { feature_df <- mat |> t() |> as.data.frame() results <- lapply(feature_df, function(x) { - FUN(x, metadata = metadata, formula = formula) + tryCatch( + FUN(x, metadata = metadata, formula = formula, ...), + error = function(e) e + ) }) + # Features where the model could not be fitted are skipped with a warning + failed <- vapply(results, inherits, logical(1L), what = "error") + if (any(failed)) { + warning( + "The model could not be fitted for ", sum(failed), " feature(s), ", + "which were skipped: ", + paste0("'", names(results)[failed], "'", collapse = ", "), + ". First error: ", conditionMessage(results[failed][[1L]]), + call. = FALSE + ) + results <- results[!failed] + } + if (length(results) == 0L) { + stop("The model could not be fitted for any feature.", call. = FALSE) + } res <- bind_rows(results, .id = "rownames") if (!is.null(p_adjust_method)) { diff --git a/man/getChisqTest.Rd b/man/getChisqTest.Rd new file mode 100644 index 0000000..fffb17b --- /dev/null +++ b/man/getChisqTest.Rd @@ -0,0 +1,48 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getChisqTest.R +\name{getChisqTest} +\alias{getChisqTest} +\title{Perform chi-square test} +\usage{ +getChisqTest(tse, formula, detection = 0, p.adjust.method = "BH", ...) +} +\arguments{ +\item{tse}{A \code{SummarizedExperiment} object.} + +\item{formula}{A formula where the LHS specifies the variable to test +(assay name, colData, or rowData variable) and the RHS specifies the +grouping variable, e.g., \code{counts ~ Group}.} + +\item{detection}{\code{Numeric scalar}. Values above this threshold are +considered present. (Default: \code{0})} + +\item{p.adjust.method}{\code{Character scalar}. Method passed to +\code{p.adjust} for multiple testing correction. (Default: \code{"BH"})} + +\item{...}{Additional arguments passed to \code{chisq_test}.} +} +\value{ +A \code{data.frame} with test results. +} +\description{ +Performs chi-square test to compare the prevalence (presence or absence) of +features between groups. +} +\details{ +A feature is present in a sample if its value is higher than +\code{detection}. The test is performed separately for each feature using the +table of groups and presence. Features that are present in all samples or +absent in all samples are skipped. P-values are adjusted for the number of +features and added to column \code{p.adj}. The chi-square approximation can +be inaccurate if there are few samples; use \code{\link{getFisherTest}} then. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +res <- getChisqTest(tse, counts ~ Geographical_location) + +} +\seealso{ +\code{\link{getFisherTest}} +} diff --git a/man/getCorrelationTest.Rd b/man/getCorrelationTest.Rd index e1d60bf..c81671f 100644 --- a/man/getCorrelationTest.Rd +++ b/man/getCorrelationTest.Rd @@ -24,9 +24,11 @@ numeric variable to correlate with, e.g., \code{counts ~ shannon}.} \code{"spearman"}, \code{"pearson"} or \code{"kendall"}. (Default: \code{"spearman"})} -\item{adjust.by}{\code{Character vector} or \code{NULL}. Names of -\code{colData} variables whose effect is removed before calculating the -correlation. (Default: \code{NULL})} +\item{adjust.by}{\code{Character vector}, \code{formula} or \code{NULL}. +Names of \code{colData} variables whose effect is removed before +calculating the correlation. A formula without the LHS, e.g., +\code{~ Gender + (1 | Subject)}, can include random effects. +(Default: \code{NULL})} \item{p.adjust.method}{\code{Character scalar}. Method passed to \code{p.adjust} for multiple testing correction. (Default: \code{"BH"})} @@ -47,11 +49,19 @@ for both variables (and covariates) are used. Features are tested only if at least three samples remain and both variables vary. P-values are adjusted for the number of features and added to column \code{p.adj}. -If \code{adjust.by} is given, the effect of the covariates is removed first: -both variables are regressed on the covariates with a linear model, and the -correlation is calculated between the residuals. The p-values are from -\code{cor_test} on the residuals, so they do not account for the degrees of -freedom used by the covariates and are slightly optimistic. +If \code{adjust.by} is given, the effect of the covariates is removed +first. For Spearman correlation, both variables are ranked within each +feature before this, so the result is the partial Spearman correlation, i.e., +the Pearson correlation of the ranks after adjustment. Both variables are +regressed on the covariates, and the correlation is calculated between the +residuals. A linear model is used, or a linear mixed model if +\code{adjust.by} is a formula with random effects, e.g., +\code{~ Gender + (1 | Subject)}. Then the residuals are what is left after +removing both the fixed and random effects, which is useful for repeated +measurements. The p-values are from \code{cor_test} on the residuals, so they +do not account for the degrees of freedom used by the covariates and are +slightly optimistic. Kendall correlation is not supported with +\code{adjust.by}. } \examples{ data(peerj13075, package = "mia") diff --git a/man/getDunnTest.Rd b/man/getDunnTest.Rd new file mode 100644 index 0000000..4ff0d35 --- /dev/null +++ b/man/getDunnTest.Rd @@ -0,0 +1,34 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getDunnTest.R +\name{getDunnTest} +\alias{getDunnTest} +\title{Perform Dunn's post-hoc test} +\usage{ +getDunnTest(tse, formula, ...) +} +\arguments{ +\item{tse}{A \code{SummarizedExperiment} object.} + +\item{formula}{A formula where the LHS specifies the variable to test +(assay name, colData, or rowData variable) and the RHS specifies the +grouping variable, e.g., \code{counts ~ Group}.} + +\item{...}{Additional arguments passed to \code{dunn_test}.} +} +\value{ +A \code{data.frame} with test results. +} +\description{ +Performs Dunn's test to compare all pairs of groups after Kruskal-Wallis +test. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +res <- getDunnTest(tse, counts ~ Geographical_location) + +} +\seealso{ +\code{\link{getKruskal}} +} diff --git a/man/getEffectSize.Rd b/man/getEffectSize.Rd index 8b8d919..933b108 100644 --- a/man/getEffectSize.Rd +++ b/man/getEffectSize.Rd @@ -4,7 +4,13 @@ \alias{getEffectSize} \title{Calculate effect sizes between groups} \usage{ -getEffectSize(tse, formula, method = c("cliff", "cohen"), pair.by = NULL, ...) +getEffectSize( + tse, + formula, + method = c("cliff", "cohen", "difference", "ratio", "log_ratio"), + pair.by = NULL, + ... +) } \arguments{ \item{tse}{A \code{SummarizedExperiment} object.} @@ -14,14 +20,15 @@ getEffectSize(tse, formula, method = c("cliff", "cohen"), pair.by = NULL, ...) grouping variable, e.g., \code{counts ~ Group}.} \item{method}{\code{Character scalar}. Effect size to calculate, -\code{"cliff"} or \code{"cohen"}. (Default: \code{"cliff"})} +\code{"cliff"}, \code{"cohen"}, \code{"difference"}, \code{"ratio"} or +\code{"log_ratio"}. (Default: \code{"cliff"})} \item{pair.by}{\code{Character scalar} or \code{NULL}. Column for pairing -samples in paired effect sizes (\code{method = "cohen"} only). Only pairs -present in both groups are used. (Default: \code{NULL})} +samples in paired effect sizes (not supported for \code{"cliff"}). Only +pairs present in both groups are used. (Default: \code{NULL})} \item{...}{Additional arguments passed to \code{effsize::cliff.delta} or -\code{effsize::cohen.d}.} +\code{effsize::cohen.d}. Not used by the other methods.} } \value{ A \code{data.frame} with one row per feature and pair of groups, @@ -29,15 +36,26 @@ and columns \code{rownames}, \code{group1}, \code{group2}, \code{effsize}, \code{conf.low}, \code{conf.high} and \code{magnitude}. } \description{ -Calculates effect sizes between each pair of groups with Cliff's delta or -Cohen's d. +Calculates effect sizes between each pair of groups: the difference, ratio +or log ratio of means, or standardized effect sizes (Cliff's delta or +Cohen's d). } \details{ +The difference (\code{"difference"}), ratio (\code{"ratio"}) and log2 ratio +(\code{"log_ratio"}) are calculated from the means of the groups, i.e., +\code{mean(group1) - mean(group2)}, \code{mean(group1) / mean(group2)} and +\code{log2(mean(group1) / mean(group2))}. The log ratio is the log2 fold +change. Values are used as they are, so the ratios are not defined if the mean +of \code{group2} is zero, and the log ratio requires positive means. These +effect sizes have no confidence intervals or magnitude. + Cliff's delta is a non-parametric effect size based on how often values in one group are larger than values in the other. Cohen's d is the difference in means scaled by the pooled standard deviation. Both are calculated with the \code{effsize} package. In paired data, Cohen's d is calculated from -the within-pair differences. Paired Cliff's delta is not supported. +the within-pair differences. Paired Cliff's delta is not supported. The +difference, ratio and log ratio of paired data are calculated from the means +of the matched values. Groups are compared pairwise in the same order as in \code{\link{getWilcoxonTest}}. Positive values mean that values are higher @@ -49,6 +67,12 @@ tse <- peerj13075 tse <- mia::agglomerateByRank(tse, "phylum") res <- getEffectSize(tse, counts ~ Geographical_location) +# Log2 fold change +res <- getEffectSize( + tse, counts ~ Geographical_location, + method = "log_ratio" +) + } \seealso{ \code{\link[effsize:cliff.delta]{effsize::cliff.delta}}, diff --git a/man/getFisherTest.Rd b/man/getFisherTest.Rd new file mode 100644 index 0000000..bc47d38 --- /dev/null +++ b/man/getFisherTest.Rd @@ -0,0 +1,47 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getFisherTest.R +\name{getFisherTest} +\alias{getFisherTest} +\title{Perform Fisher's exact test} +\usage{ +getFisherTest(tse, formula, detection = 0, p.adjust.method = "BH", ...) +} +\arguments{ +\item{tse}{A \code{SummarizedExperiment} object.} + +\item{formula}{A formula where the LHS specifies the variable to test +(assay name, colData, or rowData variable) and the RHS specifies the +grouping variable, e.g., \code{counts ~ Group}.} + +\item{detection}{\code{Numeric scalar}. Values above this threshold are +considered present. (Default: \code{0})} + +\item{p.adjust.method}{\code{Character scalar}. Method passed to +\code{p.adjust} for multiple testing correction. (Default: \code{"BH"})} + +\item{...}{Additional arguments passed to \code{fisher_test}.} +} +\value{ +A \code{data.frame} with test results. +} +\description{ +Performs Fisher's exact test to compare the prevalence (presence or absence) +of features between groups. +} +\details{ +A feature is present in a sample if its value is higher than +\code{detection}. The test is performed separately for each feature using the +table of groups and presence. Features that are present in all samples or +absent in all samples are skipped. P-values are adjusted for the number of +features and added to column \code{p.adj}. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +res <- getFisherTest(tse, counts ~ Geographical_location) + +} +\seealso{ +\code{\link{getChisqTest}} +} diff --git a/man/getFriedmanTest.Rd b/man/getFriedmanTest.Rd new file mode 100644 index 0000000..7517f6b --- /dev/null +++ b/man/getFriedmanTest.Rd @@ -0,0 +1,38 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getFriedmanTest.R +\name{getFriedmanTest} +\alias{getFriedmanTest} +\title{Perform Friedman test} +\usage{ +getFriedmanTest(tse, formula, pair.by, ...) +} +\arguments{ +\item{tse}{A \code{SummarizedExperiment} object.} + +\item{formula}{A formula where the LHS specifies the variable to test +(assay name, colData, or rowData variable) and the RHS specifies the +grouping variable, e.g., \code{counts ~ Time}.} + +\item{pair.by}{\code{Character scalar}. Column for pairing samples.} + +\item{...}{Additional arguments passed to \code{friedman_test}.} +} +\value{ +A \code{data.frame} with test results. +} +\description{ +Performs Friedman test to compare values between two or more paired groups, +e.g., repeated measurements from the same subjects. +} +\details{ +The test is performed separately for each feature. Only pairing IDs present +in all groups of the feature are used. +} +\examples{ +# Subjects measured at three timepoints +data(Kumaraswamy2024, package = "miaTime") +tse <- Kumaraswamy2024 +tse$timepoint <- factor(tse$timepoint) +res <- getFriedmanTest(tse, signal ~ timepoint, pair.by = "subject") + +} diff --git a/man/getGlm.Rd b/man/getGlm.Rd new file mode 100644 index 0000000..0363c3d --- /dev/null +++ b/man/getGlm.Rd @@ -0,0 +1,87 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getGlm.R +\name{getGlm} +\alias{getGlm} +\title{Fit generalized linear model per feature} +\usage{ +getGlm( + tse, + formula, + family = poisson(), + offset = NULL, + p_adjust_method = "BH", + ... +) +} +\arguments{ +\item{tse}{A \code{SummarizedExperiment} object.} + +\item{formula}{A formula where the LHS specifies the assay or colData +variable and the RHS specifies variables from \code{colData(tse)}, +e.g., \code{counts ~ Group}.} + +\item{family}{A family object or \code{"negbin"}. (Default: +\code{poisson()})} + +\item{offset}{\code{Character scalar}, \code{numeric vector} or \code{NULL}. +Offset of the model. Either the name of a numeric column in +\code{colData(tse)} or a vector with a value for each sample. If +\code{NULL}, no offset is used. (Default: \code{NULL})} + +\item{p_adjust_method}{\code{Character scalar} or \code{NULL}. Method passed +to \code{p.adjust} for multiple testing correction. If \code{NULL}, no +adjusted p-values are added. (Default: \code{"BH"})} + +\item{...}{Additional arguments passed to \code{glm} (or \code{glm.nb}).} +} +\value{ +A \code{data.frame} with per-feature model coefficients, p-values, +and optionally adjusted p-values in column \code{q_value}. +} +\description{ +Fits a generalized linear model (GLM) per feature. The distribution +(likelihood) of the abundances is chosen +with \code{family}, e.g., Poisson or negative binomial for counts, binomial +for presence, or Gamma for positive continuous values. +} +\details{ +The model is fitted with \code{\link[stats]{glm}}. The \code{family} +argument is a family object, e.g., \code{poisson()}, \code{quasipoisson()}, +\code{binomial()}, \code{Gamma(link = "log")} or \code{gaussian()}. Use +\code{family = "negbin"} for a negative binomial model fitted with +\code{\link[MASS]{glm.nb}}, which estimates the dispersion of each feature. + +An offset can be given with \code{offset}, e.g., the log of the library size +of each sample for a Poisson or negative binomial model, so that the model +is for the abundance relative to the library size. The offset is added to +the linear predictor as such, so it must be on the scale of the link +function. + +The estimates are on the scale of the link function, e.g., the log +scale for a Poisson or negative binomial model, and the log odds for a +binomial model. The \code{gaussian()} family gives the same result as +\code{\link{getLm}}. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +# Poisson model for counts +res <- getGlm(tse, counts ~ Geographical_location) + +# Negative binomial model for overdispersed counts +res <- getGlm(tse, counts ~ Geographical_location, family = "negbin") + +# Offset: the log of the library size of each sample +tse$log_total <- log(colSums(SummarizedExperiment::assay(tse, "counts"))) +res <- getGlm(tse, counts ~ Geographical_location, offset = "log_total") + +# Binomial model (logistic regression) for presence +tse <- mia::transformAssay(tse, method = "pa") +res <- getGlm(tse, pa ~ Geographical_location, family = binomial()) + +} +\seealso{ +\code{\link{getLm}}, \code{\link{getFirth}} +} diff --git a/man/getLeveneTest.Rd b/man/getLeveneTest.Rd new file mode 100644 index 0000000..43520d1 --- /dev/null +++ b/man/getLeveneTest.Rd @@ -0,0 +1,31 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getLeveneTest.R +\name{getLeveneTest} +\alias{getLeveneTest} +\title{Perform Levene's test} +\usage{ +getLeveneTest(tse, formula, ...) +} +\arguments{ +\item{tse}{A \code{SummarizedExperiment} object.} + +\item{formula}{A formula where the LHS specifies the variable to test +(assay name, colData, or rowData variable) and the RHS specifies the +grouping variable, e.g., \code{counts ~ Group}.} + +\item{...}{Additional arguments passed to \code{levene_test}.} +} +\value{ +A \code{data.frame} with test results. +} +\description{ +Performs Levene's test to check whether the variances are equal between +groups. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +res <- getLeveneTest(tse, counts ~ Geographical_location) + +} diff --git a/man/getLm.Rd b/man/getLm.Rd index d253dcd..e90beeb 100644 --- a/man/getLm.Rd +++ b/man/getLm.Rd @@ -11,7 +11,8 @@ getLm(tse, formula, p_adjust_method = "BH", ...) \item{formula}{A formula where the LHS specifies the assay or colData variable and the RHS specifies variables from \code{colData(tse)}, -e.g., \code{rclr ~ Group}.} +e.g., \code{rclr ~ Group}. Random effects are given as in \code{lme4}, +e.g., \code{rclr ~ Group + (1 | Subject)}.} \item{p_adjust_method}{\code{Character scalar} or \code{NULL}. Method passed to \code{p.adjust} for multiple testing correction. If \code{NULL}, no @@ -25,6 +26,14 @@ and optionally adjusted p-values in column \code{q_value}. } \description{ Fits a linear model per feature using wide-format data and sample metadata. +Random effects can be added to the formula to fit a linear mixed model, e.g., +for repeated measurements from the same subject. +} +\details{ +If the formula has random effects, as in \code{lme4}, e.g., +\code{rclr ~ Group + (1 | Subject)}, a linear mixed model is fitted with +\code{lmerTest::lmer}, which provides p-values for the fixed effects. +Otherwise, a linear model is fitted with \code{lm}. } \examples{ data(peerj13075, package = "mia") @@ -33,4 +42,11 @@ tse <- mia::agglomerateByRank(tse, "phylum") tse <- mia::transformAssay(tse, method = "rclr") res <- getLm(tse, rclr ~ Geographical_location) +# Mixed model for subjects measured at several timepoints +data(Kumaraswamy2024, package = "miaTime") +tse <- Kumaraswamy2024[1:10, ] +tse$timepoint <- factor(tse$timepoint) +tse <- mia::transformAssay(tse, assay.type = "signal", method = "rclr") +res <- getLm(tse, rclr ~ timepoint + (1 | subject)) + } diff --git a/man/getPermdisp.Rd b/man/getPermdisp.Rd new file mode 100644 index 0000000..68d756a --- /dev/null +++ b/man/getPermdisp.Rd @@ -0,0 +1,52 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getPermdisp.R +\name{getPermdisp} +\alias{getPermdisp} +\title{Perform test for homogeneity of multivariate dispersions} +\usage{ +getPermdisp(tse, formula, method = "bray", permutations = 999L, ...) +} +\arguments{ +\item{tse}{A \code{SummarizedExperiment} object.} + +\item{formula}{A formula where the LHS specifies the assay name and the RHS +specifies the grouping variable from \code{colData}, e.g., +\code{counts ~ Group}.} + +\item{method}{\code{Character scalar}. Dissimilarity index passed to +\code{vegdist}. (Default: \code{"bray"})} + +\item{permutations}{\code{Integer scalar}. Number of permutations. +(Default: \code{999})} + +\item{...}{Additional arguments passed to \code{permutest}.} +} +\value{ +A \code{data.frame} with columns \code{n}, \code{Df}, \code{F} and +\code{p}. +} +\description{ +Performs PERMDISP to test whether the dispersion (variability) of the +composition differs between groups. +} +\details{ +PERMANOVA (\code{\link{getPermanova}}) is also sensitive to differences in +dispersion between groups, so PERMDISP is a useful companion test. A +distance matrix between samples is calculated from the assay with +\code{\link[vegan:vegdist]{vegan::vegdist}}, distances to the group centroids +are calculated with +\code{\link[vegan:betadisper]{vegan::betadisper}}, and the groups are +compared with a permutation test. The p-value is based on permutations, so +set a seed for reproducible results. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +set.seed(1) +res <- getPermdisp(tse, counts ~ Geographical_location) + +} +\seealso{ +\code{\link[vegan:betadisper]{vegan::betadisper}} +} diff --git a/man/getShapiroTest.Rd b/man/getShapiroTest.Rd new file mode 100644 index 0000000..3162829 --- /dev/null +++ b/man/getShapiroTest.Rd @@ -0,0 +1,55 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getShapiroTest.R +\name{getShapiroTest} +\alias{getShapiroTest} +\title{Perform Shapiro-Wilk test on residuals} +\usage{ +getShapiroTest(tse, formula, p.adjust.method = "BH") +} +\arguments{ +\item{tse}{A \code{SummarizedExperiment} object.} + +\item{formula}{A formula where the LHS specifies the variable to test +(assay name or colData variable) and the RHS specifies variables from +\code{colData(tse)}, e.g., \code{counts ~ Group}. Random effects are +given as in \code{lme4}.} + +\item{p.adjust.method}{\code{Character scalar}. Method passed to +\code{p.adjust} for multiple testing correction. (Default: \code{"BH"})} +} +\value{ +A \code{data.frame} with test results. +} +\description{ +Performs Shapiro-Wilk test to check whether the residuals of a model are +normally distributed. +} +\details{ +The normality assumption concerns the residuals, not the values. For each +feature, a model is fitted as in \code{\link{getLm}}, and its residuals are tested. By default, a linear +model \code{variable ~ group} is fitted, and the residuals are the +differences from the group means. The formula can have several variables and, +as in \code{getLm}, random effects, e.g., \code{counts ~ Group + (1 | Subject)}, +which fits a linear mixed model. + +Features are tested only if they have at least three values and the +residuals vary. Features where the model cannot be fitted are skipped with a +warning. P-values are adjusted for the number of features and added to column +\code{p.adj}. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +res <- getShapiroTest(tse, counts ~ Geographical_location) + +# Mixed model for subjects measured at several timepoints +data(Kumaraswamy2024, package = "miaTime") +tse <- Kumaraswamy2024[1:10, ] +tse$timepoint <- factor(tse$timepoint) +res <- getShapiroTest(tse, signal ~ timepoint + (1 | subject)) + +} +\seealso{ +\code{\link{getLeveneTest}}, \code{\link{getLm}} +} diff --git a/man/getTukeyTest.Rd b/man/getTukeyTest.Rd new file mode 100644 index 0000000..08ecd54 --- /dev/null +++ b/man/getTukeyTest.Rd @@ -0,0 +1,34 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getTukeyTest.R +\name{getTukeyTest} +\alias{getTukeyTest} +\title{Perform Tukey's HSD post-hoc test} +\usage{ +getTukeyTest(tse, formula, ...) +} +\arguments{ +\item{tse}{A \code{SummarizedExperiment} object.} + +\item{formula}{A formula where the LHS specifies the variable to test +(assay name, colData, or rowData variable) and the RHS specifies the +grouping variable, e.g., \code{counts ~ Group}.} + +\item{...}{Additional arguments passed to \code{tukey_hsd}.} +} +\value{ +A \code{data.frame} with test results. +} +\description{ +Performs Tukey's honest significant difference test to compare all pairs of +groups after ANOVA. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +res <- getTukeyTest(tse, counts ~ Geographical_location) + +} +\seealso{ +\code{\link{getAnova}} +} diff --git a/man/getWilcoxonTest.Rd b/man/getWilcoxonTest.Rd index e5983de..1261a5d 100644 --- a/man/getWilcoxonTest.Rd +++ b/man/getWilcoxonTest.Rd @@ -4,13 +4,7 @@ \alias{getWilcoxonTest} \title{Perform Wilcoxon rank-sum test} \usage{ -getWilcoxonTest( - tse, - formula, - effect.size = c("cliff", "cohen"), - pair.by = NULL, - ... -) +getWilcoxonTest(tse, formula, pair.by = NULL, ...) } \arguments{ \item{tse}{A \code{SummarizedExperiment} object.} @@ -19,30 +13,25 @@ getWilcoxonTest( (assay name, colData, or rowData variable) and the RHS specifies the grouping variable, e.g., \code{counts ~ Group}.} -\item{effect.size}{\code{Character scalar}. Effect size from -\code{\link{getEffectSize}} added to the results, \code{"cliff"} or -\code{"cohen"}. Paired Cliff's delta is not supported. (Default: -\code{"cliff"})} - \item{pair.by}{\code{Character scalar} or \code{NULL}. Column for pairing samples in paired tests. (Default: \code{NULL})} \item{...}{Additional arguments passed to \code{wilcox_test}.} } \value{ -A \code{data.frame} with test results and effect size. +A \code{data.frame} with test results. } \description{ Performs Wilcoxon rank-sum test (Mann-Whitney U) to compare values between -two groups. An effect size is added to the results. +two groups. } \details{ Without \code{pair.by}, the unpaired Wilcoxon rank-sum test is used. With \code{pair.by}, samples are matched and the paired signed-rank test is used. If there are more than two groups, all pairs are compared. -The effect size from \code{\link{getEffectSize}} is added to the results. -Paired Cliff's delta is not supported. +The test does not calculate an effect size. Use +\code{\link{getEffectSize}} as a separate step. } \examples{ data(peerj13075, package = "mia") @@ -50,10 +39,4 @@ tse <- peerj13075 tse <- mia::agglomerateByRank(tse, "phylum") res <- getWilcoxonTest(tse, counts ~ Geographical_location) -# Use Cohen's d instead of Cliff's delta -res <- getWilcoxonTest( - tse, counts ~ Geographical_location, - effect.size = "cohen" -) - } diff --git a/tests/testthat/test-getChisqTest.R b/tests/testthat/test-getChisqTest.R new file mode 100644 index 0000000..b406e8f --- /dev/null +++ b/tests/testthat/test-getChisqTest.R @@ -0,0 +1,45 @@ +# Tests for getChisqTest +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +test_that("getChisqTest returns one row per tested feature", { + res <- getChisqTest(tse, counts ~ Geographical_location) + expect_s3_class(res, "data.frame") + expect_true(all(c("rownames", "n", "statistic", "df", "p", "p.adj") %in% + names(res))) + expect_false(anyDuplicated(res$rownames) > 0) +}) + +test_that("getChisqTest matches chisq.test on presence", { + res <- getChisqTest(tse, counts ~ Geographical_location) + feature <- res$rownames[[1L]] + + counts <- SummarizedExperiment::assay(tse, "counts")[feature, ] + expected <- chisq.test(table(tse$Geographical_location, counts > 0)) + + expect_equal(res$statistic[[1L]], unname(expected$statistic)) + expect_equal(res$p[[1L]], expected$p.value) + expect_equal(res$df[[1L]], unname(expected$parameter)) +}) + +test_that("getChisqTest skips features without variation in presence", { + counts <- SummarizedExperiment::assay(tse, "counts") + counts["Firmicutes", ] <- 1 + SummarizedExperiment::assay(tse, "counts") <- counts + + res <- getChisqTest(tse, counts ~ Geographical_location) + expect_false("Firmicutes" %in% res$rownames) +}) + +test_that("getChisqTest adjusts p-values", { + res <- getChisqTest(tse, counts ~ Geographical_location) + expect_equal(res$p.adj, stats::p.adjust(res$p, method = "BH")) +}) + +test_that("getChisqTest fails with multiple RHS vars", { + expect_error( + getChisqTest(tse, counts ~ Geographical_location + Gender), + "exactly one" + ) +}) diff --git a/tests/testthat/test-getCorrelationTest.R b/tests/testthat/test-getCorrelationTest.R index 6a8e7e7..a8d734d 100644 --- a/tests/testthat/test-getCorrelationTest.R +++ b/tests/testthat/test-getCorrelationTest.R @@ -29,8 +29,8 @@ test_that("getCorrelationTest matches cor.test for each feature", { method = "pearson" ) - # rstatix rounds the correlation coefficient to two decimals - expect_equal(unname(row$cor), round(unname(expected$estimate), 2)) + # rstatix rounds the correlation coefficient to two significant digits + expect_equal(unname(row$cor), signif(unname(expected$estimate), 2)) expect_equal(row$p, expected$p.value) }) @@ -59,7 +59,7 @@ test_that("getCorrelationTest ignores missing values", { keep <- !is.na(tse$score) expected <- stats::cor.test(counts[keep], tse$score[keep]) - expect_equal(unname(row$cor), round(unname(expected$estimate), 2)) + expect_equal(unname(row$cor), signif(unname(expected$estimate), 2)) }) test_that("getCorrelationTest skips features without variance", { @@ -106,7 +106,7 @@ test_that("getCorrelationTest correlates residuals with adjust.by", { )) |> residuals() expected <- stats::cor.test(counts_adjusted, score_adjusted) - expect_equal(unname(row$cor), round(unname(expected$estimate), 2)) + expect_equal(unname(row$cor), signif(unname(expected$estimate), 2)) expect_equal(row$p, expected$p.value) }) @@ -129,6 +129,35 @@ test_that("getCorrelationTest removes the effect of a covariate", { expect_lt(abs(adjusted[adjusted$rownames == "Firmicutes", ]$cor), 0.5) }) +test_that("getCorrelationTest calculates partial Spearman correlation", { + res <- getCorrelationTest( + tse, counts ~ score, + adjust.by = c("Gender", "Diet") + ) + row <- res[res$rownames == "Firmicutes", ] + + md <- as.data.frame(SummarizedExperiment::colData(tse)) + md$counts <- rank(SummarizedExperiment::assay(tse, "counts")["Firmicutes", ]) + md$score <- rank(tse$score) + counts_adjusted <- lm(counts ~ Gender + Diet, data = md) |> residuals() + score_adjusted <- lm(score ~ Gender + Diet, data = md) |> residuals() + expected <- stats::cor.test(counts_adjusted, score_adjusted) + + expect_equal(unname(row$cor), signif(unname(expected$estimate), 2)) + expect_equal(row$p, expected$p.value) + expect_true(all(c("p.adj", "var1", "var2") %in% names(res))) +}) + +test_that("getCorrelationTest rejects Kendall with adjust.by", { + expect_error( + getCorrelationTest( + tse, counts ~ score, + method = "kendall", adjust.by = "Gender" + ), + "Kendall" + ) +}) + test_that("getCorrelationTest ignores samples with missing covariates", { tse$Gender[1L] <- NA res <- getCorrelationTest( @@ -146,3 +175,68 @@ test_that("getCorrelationTest fails with unknown covariate", { "not found" ) }) + +################################################################################ +# Adjustment with a mixed model +################################################################################ + +# Subjects measured at three timepoints; subset of features for speed +data(Kumaraswamy2024, package = "miaTime") +time_tse <- Kumaraswamy2024[1:10, ] +time_tse$timepoint <- factor(time_tse$timepoint) +set.seed(1) +time_tse$score <- rnorm(ncol(time_tse)) + +test_that("getCorrelationTest correlates residuals of a mixed model", { + res <- getCorrelationTest( + time_tse, signal ~ score, + method = "pearson", adjust.by = ~ timepoint + (1 | subject) + ) + feature <- rownames(time_tse)[[1L]] + row <- res[res$rownames == feature, ] + + data_model <- data.frame( + signal = SummarizedExperiment::assay(time_tse, "signal")[feature, ], + score = time_tse$score, + timepoint = time_tse$timepoint, + subject = time_tse$subject + ) + signal_adjusted <- lme4::lmer( + signal ~ timepoint + (1 | subject), + data = data_model + ) |> residuals() + score_adjusted <- lme4::lmer( + score ~ timepoint + (1 | subject), + data = data_model + ) |> residuals() + expected <- stats::cor.test(signal_adjusted, score_adjusted) + + expect_equal(unname(row$cor), signif(unname(expected$estimate), 2)) + expect_equal(row$p, expected$p.value) +}) + +test_that("getCorrelationTest accepts a formula without random effects", { + from_formula <- getCorrelationTest( + time_tse, signal ~ score, + method = "pearson", adjust.by = ~timepoint + ) + from_names <- getCorrelationTest( + time_tse, signal ~ score, + method = "pearson", adjust.by = "timepoint" + ) + + expect_equal(from_formula, from_names) +}) + +test_that("getCorrelationTest mixed model differs from a linear model", { + mixed <- getCorrelationTest( + time_tse, signal ~ score, + method = "pearson", adjust.by = ~ timepoint + (1 | subject) + ) + linear <- getCorrelationTest( + time_tse, signal ~ score, + method = "pearson", adjust.by = "timepoint" + ) + + expect_false(isTRUE(all.equal(mixed$p, linear$p))) +}) diff --git a/tests/testthat/test-getDunnTest.R b/tests/testthat/test-getDunnTest.R new file mode 100644 index 0000000..6a01488 --- /dev/null +++ b/tests/testthat/test-getDunnTest.R @@ -0,0 +1,37 @@ +# Tests for getDunnTest +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +test_that("getDunnTest returns one row per feature and pair of groups", { + res <- getDunnTest(tse, counts ~ Geographical_location) + expect_s3_class(res, "data.frame") + expect_true(all(c("rownames", "group1", "group2", "p", "p.adj") %in% + names(res))) + expect_false(anyDuplicated(paste(res$rownames, res$group1, res$group2)) > 0) +}) + +test_that("getDunnTest matches dunn_test for each feature", { + res <- getDunnTest(tse, counts ~ Geographical_location) + row <- res[res$rownames == "Firmicutes" & + res$group1 == "Ahmednagar" & res$group2 == "Pune", ] + + df <- data.frame( + counts = SummarizedExperiment::assay(tse, "counts")["Firmicutes", ], + group = tse$Geographical_location + ) + expected <- rstatix::dunn_test(df, counts ~ group) + expected <- expected[expected$group1 == "Ahmednagar" & + expected$group2 == "Pune", ] + + expect_equal(row$statistic, expected$statistic) + expect_equal(row$p, expected$p) + expect_equal(row$p.adj, expected$p.adj) +}) + +test_that("getDunnTest fails with multiple RHS vars", { + expect_error( + getDunnTest(tse, counts ~ Geographical_location + Gender), + "exactly one" + ) +}) diff --git a/tests/testthat/test-getEffectSize.R b/tests/testthat/test-getEffectSize.R index eb7827e..572702e 100644 --- a/tests/testthat/test-getEffectSize.R +++ b/tests/testthat/test-getEffectSize.R @@ -53,6 +53,86 @@ test_that("getEffectSize requires one grouping variable", { ) }) +################################################################################ +# Difference, ratio and log ratio +################################################################################ + +test_that("getEffectSize calculates the difference and ratio of means", { + counts <- SummarizedExperiment::assay(tse, "counts")["Firmicutes", ] + in_group <- function(group) { + counts[tse$Geographical_location == group] + } + expected_means <- c( + Ahmednagar = mean(in_group("Ahmednagar")), + Pune = mean(in_group("Pune")) + ) + + get_row <- function(method) { + res <- getEffectSize( + tse, counts ~ Geographical_location, + method = method + ) + res[res$rownames == "Firmicutes" & + res$group1 == "Ahmednagar" & res$group2 == "Pune", ] + } + + expect_equal( + get_row("difference")$effsize, + expected_means[["Ahmednagar"]] - expected_means[["Pune"]] + ) + expect_equal( + get_row("ratio")$effsize, + expected_means[["Ahmednagar"]] / expected_means[["Pune"]] + ) + expect_equal( + get_row("log_ratio")$effsize, + log2(expected_means[["Ahmednagar"]] / expected_means[["Pune"]]) + ) +}) + +test_that("getEffectSize has no interval or magnitude for ratios", { + for (method in c("difference", "ratio", "log_ratio")) { + res <- getEffectSize( + tse, counts ~ Geographical_location, + method = method + ) + expect_true(all(is.na(res$conf.low))) + expect_true(all(is.na(res$conf.high))) + expect_true(all(is.na(res$magnitude))) + expect_false(any(is.na(res$effsize) & res$rownames == "Firmicutes")) + } +}) + +test_that("getEffectSize log ratio is the log2 of the ratio", { + ratio <- getEffectSize( + tse, counts ~ Geographical_location, + method = "ratio" + ) + log_ratio <- getEffectSize( + tse, counts ~ Geographical_location, + method = "log_ratio" + ) + + expect_equal(log_ratio$effsize, log2(ratio$effsize)) +}) + +test_that("getEffectSize gives positive difference if group1 is higher", { + counts <- SummarizedExperiment::assay(tse, "counts") + counts["Firmicutes", ] <- ifelse( + tse$Geographical_location == "Ahmednagar", 100, 10 + ) + SummarizedExperiment::assay(tse, "counts") <- counts + + res <- getEffectSize( + tse, counts ~ Geographical_location, + method = "difference" + ) + row <- res[res$rownames == "Firmicutes" & + res$group1 == "Ahmednagar" & res$group2 == "Pune", ] + + expect_equal(row$effsize, 90) +}) + ################################################################################ # NA handling and group checks ################################################################################ @@ -122,31 +202,38 @@ test_that("getEffectSize gives positive values if group1 is higher", { # Paired data ################################################################################ -# Two groups with the same number of samples; samples are paired by order -paired_tse <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] -paired_tse$id <- ave( - seq_len(ncol(paired_tse)), paired_tse$Geographical_location, - FUN = seq_along -) +# Subjects measured at several timepoints +data(Kumaraswamy2024, package = "miaTime") +time_tse <- Kumaraswamy2024 +time_tse$timepoint <- factor(time_tse$timepoint) +paired_tse <- time_tse[, time_tse$timepoint %in% c("1", "2")] + +# Values of the first two timepoints for subjects measured at both +get_paired_values <- function(tse, feature) { + values <- SummarizedExperiment::assay(tse, "signal")[feature, ] + first <- tse$timepoint == "1" + second <- tse$timepoint == "2" + subjects <- intersect(tse$subject[first], tse$subject[second]) + list( + first = values[first][match(subjects, tse$subject[first])], + second = values[second][match(subjects, tse$subject[second])] + ) +} test_that("getEffectSize calculates paired Cohen's d", { res <- getEffectSize( - paired_tse, counts ~ Geographical_location, - method = "cohen", pair.by = "id" + paired_tse, signal ~ timepoint, + method = "cohen", pair.by = "subject" ) - row <- res[res$rownames == "Firmicutes", ] + feature <- rownames(paired_tse)[[1L]] + row <- res[res$rownames == feature, ] - counts <- SummarizedExperiment::assay(paired_tse, "counts")["Firmicutes", ] - is_first <- paired_tse$Geographical_location == "Ahmednagar" - expected <- effsize::cohen.d( - counts[is_first][order(paired_tse$id[is_first])], - counts[!is_first][order(paired_tse$id[!is_first])], - paired = TRUE - ) + values <- get_paired_values(paired_tse, feature) + expected <- effsize::cohen.d(values$first, values$second, paired = TRUE) expect_equal(nrow(res), nrow(paired_tse)) - expect_equal(row$group1, "Ahmednagar") - expect_equal(row$group2, "Nashik") + expect_equal(row$group1, "1") + expect_equal(row$group2, "2") expect_equal(row$effsize, unname(expected$estimate)) expect_equal(c(row$conf.low, row$conf.high), unname(expected$conf.int)) }) @@ -155,27 +242,55 @@ test_that("getEffectSize uses only pairs present in both groups", { # Remove one sample so that its pair has no partner removed <- paired_tse[, -1L] res <- getEffectSize( - removed, counts ~ Geographical_location, - method = "cohen", pair.by = "id" + removed, signal ~ timepoint, + method = "cohen", pair.by = "subject" ) - row <- res[res$rownames == "Firmicutes", ] + feature <- rownames(paired_tse)[[1L]] + row <- res[res$rownames == feature, ] - counts <- SummarizedExperiment::assay(paired_tse, "counts")["Firmicutes", ] - is_first <- paired_tse$Geographical_location == "Ahmednagar" - first <- counts[is_first][order(paired_tse$id[is_first])] - second <- counts[!is_first][order(paired_tse$id[!is_first])] - expected <- effsize::cohen.d(first[-1L], second[-1L], paired = TRUE) + values <- get_paired_values(removed, feature) + expected <- effsize::cohen.d(values$first, values$second, paired = TRUE) + expect_lt( + length(values$first), + length(get_paired_values(paired_tse, feature)$first) + ) expect_equal(row$effsize, unname(expected$estimate)) }) test_that("getEffectSize does not support paired Cliff's delta", { expect_warning( res <- getEffectSize( - paired_tse, counts ~ Geographical_location, - method = "cliff", pair.by = "id" + paired_tse, signal ~ timepoint, + method = "cliff", pair.by = "subject" ), "Paired Cliff's delta is not supported" ) expect_null(res) }) + +test_that("getEffectSize calculates paired differences and ratios", { + feature <- rownames(paired_tse)[[1L]] + values <- get_paired_values(paired_tse, feature) + + get_effect_size <- function(method) { + res <- getEffectSize( + paired_tse, signal ~ timepoint, + method = method, pair.by = "subject" + ) + res[res$rownames == feature, ]$effsize + } + + expect_equal( + get_effect_size("difference"), + mean(values$first - values$second) + ) + expect_equal( + get_effect_size("ratio"), + mean(values$first) / mean(values$second) + ) + expect_equal( + get_effect_size("log_ratio"), + log2(mean(values$first) / mean(values$second)) + ) +}) diff --git a/tests/testthat/test-getFisherTest.R b/tests/testthat/test-getFisherTest.R new file mode 100644 index 0000000..67ffd7d --- /dev/null +++ b/tests/testthat/test-getFisherTest.R @@ -0,0 +1,55 @@ +# Tests for getFisherTest +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +test_that("getFisherTest returns one row per tested feature", { + res <- getFisherTest(tse, counts ~ Geographical_location) + expect_s3_class(res, "data.frame") + expect_true(all(c("rownames", "n", "p", "p.adj") %in% names(res))) + expect_false(anyDuplicated(res$rownames) > 0) +}) + +test_that("getFisherTest matches fisher.test on presence", { + res <- getFisherTest(tse, counts ~ Geographical_location) + feature <- res$rownames[[1L]] + + counts <- SummarizedExperiment::assay(tse, "counts")[feature, ] + expected <- fisher.test(table(tse$Geographical_location, counts > 0)) + + expect_equal(res$p[[1L]], expected$p.value) + expect_equal(res$n[[1L]], ncol(tse)) +}) + +test_that("getFisherTest skips features without variation in presence", { + counts <- SummarizedExperiment::assay(tse, "counts") + counts["Firmicutes", ] <- 1 + SummarizedExperiment::assay(tse, "counts") <- counts + + res <- getFisherTest(tse, counts ~ Geographical_location) + expect_false("Firmicutes" %in% res$rownames) +}) + +test_that("getFisherTest uses the detection threshold", { + low <- getFisherTest(tse, counts ~ Geographical_location) + high <- getFisherTest(tse, counts ~ Geographical_location, detection = 100) + + feature <- high$rownames[[1L]] + counts <- SummarizedExperiment::assay(tse, "counts")[feature, ] + expected <- fisher.test(table(tse$Geographical_location, counts > 100)) + + expect_equal(high$p[[1L]], expected$p.value) + expect_false(isTRUE(all.equal(low$p, high$p))) +}) + +test_that("getFisherTest adjusts p-values", { + res <- getFisherTest(tse, counts ~ Geographical_location) + expect_equal(res$p.adj, stats::p.adjust(res$p, method = "BH")) +}) + +test_that("getFisherTest fails with multiple RHS vars", { + expect_error( + getFisherTest(tse, counts ~ Geographical_location + Gender), + "exactly one" + ) +}) diff --git a/tests/testthat/test-getFriedmanTest.R b/tests/testthat/test-getFriedmanTest.R new file mode 100644 index 0000000..e0a6f94 --- /dev/null +++ b/tests/testthat/test-getFriedmanTest.R @@ -0,0 +1,61 @@ +# Tests for getFriedmanTest +# Subjects measured at three timepoints +data(Kumaraswamy2024, package = "miaTime") +tse <- Kumaraswamy2024 +tse$timepoint <- factor(tse$timepoint) + +# Subjects measured at all timepoints +complete_subjects <- Reduce( + intersect, + lapply(levels(tse$timepoint), function(timepoint) { + tse$subject[tse$timepoint == timepoint] + }) +) + +test_that("getFriedmanTest returns one row per feature", { + res <- getFriedmanTest(tse, signal ~ timepoint, pair.by = "subject") + expect_s3_class(res, "data.frame") + expect_true(all(c("rownames", "n", "statistic", "df", "p") %in% + names(res))) + expect_false(anyDuplicated(res$rownames) > 0) + expect_equal(nrow(res), nrow(tse)) +}) + +test_that("getFriedmanTest matches friedman.test", { + res <- getFriedmanTest(tse, signal ~ timepoint, pair.by = "subject") + feature <- rownames(tse)[[1L]] + row <- res[res$rownames == feature, ] + + keep <- tse$subject %in% complete_subjects + values <- tapply( + SummarizedExperiment::assay(tse, "signal")[feature, keep], + list(tse$subject[keep], tse$timepoint[keep]), + sum + ) + expected <- friedman.test(values[complete_subjects, ]) + + expect_equal(unname(row$statistic), unname(expected$statistic)) + expect_equal(row$p, expected$p.value) +}) + +test_that("getFriedmanTest uses only pairing IDs present in all groups", { + res <- getFriedmanTest(tse, signal ~ timepoint, pair.by = "subject") + + # Subjects with missing timepoints are left out + expect_lt(length(complete_subjects), length(unique(tse$subject))) + expect_true(all(res$n == length(complete_subjects))) +}) + +test_that("getFriedmanTest fails with multiple RHS vars", { + expect_error( + getFriedmanTest(tse, signal ~ timepoint + sex, pair.by = "subject"), + "exactly one" + ) +}) + +test_that("getFriedmanTest fails with unknown pair.by", { + expect_error( + getFriedmanTest(tse, signal ~ timepoint, pair.by = "nonexistent"), + "not found" + ) +}) diff --git a/tests/testthat/test-getGlm.R b/tests/testthat/test-getGlm.R new file mode 100644 index 0000000..9bf8a75 --- /dev/null +++ b/tests/testthat/test-getGlm.R @@ -0,0 +1,128 @@ +# Tests for getGlm +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +tse <- mia::transformAssay(tse, method = "pa") + +test_that("getGlm returns data frame", { + res <- getGlm(tse, counts ~ Geographical_location) + expect_s3_class(res, "data.frame") + expect_true(all(c( + "rownames", "variable", "estimate", "p_value", + "q_value" + ) %in% names(res))) + expect_false("(Intercept)" %in% res$variable) +}) + +test_that("getGlm allows disabling p-value adjustment", { + res <- getGlm(tse, counts ~ Geographical_location, p_adjust_method = NULL) + expect_false("q_value" %in% names(res)) +}) + +test_that("getGlm matches glm with the Poisson family", { + res <- getGlm(tse, counts ~ Geographical_location) + feature <- rownames(tse)[[2L]] + row <- res[res$rownames == feature & + res$variable == "Geographical_locationNashik", ] + data_model <- data.frame( + abundance = SummarizedExperiment::assay(tse, "counts")[feature, ], + group = tse$Geographical_location + ) + fit <- summary(glm(abundance ~ group, poisson(), data_model))$coefficients + expect_equal(row$estimate, unname(fit["groupNashik", "Estimate"])) + expect_equal(row$p_value, unname(fit["groupNashik", "Pr(>|z|)"])) +}) + +test_that("getGlm matches glm.nb with the negative binomial family", { + res <- getGlm(tse, counts ~ Geographical_location, family = "negbin") + feature <- rownames(tse)[[2L]] + row <- res[res$rownames == feature & + res$variable == "Geographical_locationNashik", ] + data_model <- data.frame( + abundance = SummarizedExperiment::assay(tse, "counts")[feature, ], + group = tse$Geographical_location + ) + fit <- summary(MASS::glm.nb(abundance ~ group, data = data_model)) + expect_equal(row$estimate, unname(fit$coefficients["groupNashik", "Estimate"])) + expect_equal(row$p_value, unname(fit$coefficients["groupNashik", "Pr(>|z|)"])) +}) + +test_that("getGlm with the Gaussian family matches getLm", { + res_glm <- getGlm( + tse, counts ~ Geographical_location, + family = gaussian() + ) + res_lm <- getLm(tse, counts ~ Geographical_location) + expect_equal(res_glm$estimate, res_lm$estimate) + expect_equal(res_glm$p_value, res_lm$p_value) +}) + +test_that("getGlm fits a logistic regression with the binomial family", { + res <- getGlm( + tse, pa ~ Geographical_location + Gender, + family = binomial(), + p_adjust_method = NULL + ) + feature <- "Bacteroidetes" + row <- res[res$rownames == feature & res$variable == "GenderMale", ] + data_model <- data.frame( + abundance = SummarizedExperiment::assay(tse, "pa")[feature, ], + group = tse$Geographical_location, gender = tse$Gender + ) + fit <- summary(glm(abundance ~ group + gender, binomial(), data_model)) + expect_equal(row$estimate, unname(fit$coefficients["genderMale", "Estimate"])) + expect_equal(row$p_value, unname(fit$coefficients["genderMale", "Pr(>|z|)"])) +}) + +test_that("getGlm uses an offset from colData or a vector", { + tse$log_total <- log(colSums(SummarizedExperiment::assay(tse, "counts"))) + res <- getGlm( + tse, counts ~ Geographical_location, + offset = "log_total", + p_adjust_method = NULL + ) + feature <- rownames(tse)[[2L]] + row <- res[res$rownames == feature & + res$variable == "Geographical_locationNashik", ] + data_model <- data.frame( + abundance = SummarizedExperiment::assay(tse, "counts")[feature, ], + group = tse$Geographical_location, log_total = tse$log_total + ) + fit <- summary(glm( + abundance ~ group + offset(log_total), poisson(), data_model + ))$coefficients + expect_equal(row$estimate, unname(fit["groupNashik", "Estimate"])) + expect_equal(row$p_value, unname(fit["groupNashik", "Pr(>|z|)"])) + # A vector gives the same result as the column + res_vector <- getGlm( + tse, counts ~ Geographical_location, + offset = tse$log_total, + p_adjust_method = NULL + ) + expect_equal(res_vector, res) + # The offset changes the result + res_none <- getGlm(tse, counts ~ Geographical_location) + expect_false(isTRUE(all.equal(res$estimate, res_none$estimate))) +}) + +test_that("getGlm uses an offset with the negative binomial family", { + tse$log_total <- log(colSums(SummarizedExperiment::assay(tse, "counts"))) + res <- getGlm( + tse, counts ~ Geographical_location, + family = "negbin", + offset = "log_total" + ) + expect_s3_class(res, "data.frame") + expect_true(all(is.finite(res$estimate))) +}) + +test_that("getGlm checks the offset", { + expect_error( + getGlm(tse, counts ~ Geographical_location, offset = "missing"), + "'offset' must be a column" + ) + expect_error( + getGlm(tse, counts ~ Geographical_location, offset = c(1, 2)), + "'offset' must be a numeric vector" + ) +}) diff --git a/tests/testthat/test-getLeveneTest.R b/tests/testthat/test-getLeveneTest.R new file mode 100644 index 0000000..de3393b --- /dev/null +++ b/tests/testthat/test-getLeveneTest.R @@ -0,0 +1,36 @@ +# Tests for getLeveneTest +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +test_that("getLeveneTest returns one row per feature", { + res <- getLeveneTest(tse, counts ~ Geographical_location) + expect_s3_class(res, "data.frame") + expect_true(all(c("rownames", "df1", "df2", "statistic", "p") %in% + names(res))) + expect_false(anyDuplicated(res$rownames) > 0) +}) + +test_that("getLeveneTest matches the test on deviations from the median", { + res <- getLeveneTest(tse, counts ~ Geographical_location) + row <- res[res$rownames == "Firmicutes", ] + + counts <- SummarizedExperiment::assay(tse, "counts")["Firmicutes", ] + group <- factor(tse$Geographical_location) + deviation <- abs(counts - ave(counts, group, FUN = median)) + expected <- anova(lm(deviation ~ group)) + + expect_equal(row$statistic, expected[["F value"]][[1L]]) + expect_equal(row$p, expected[["Pr(>F)"]][[1L]]) +}) + +test_that("getLeveneTest does not warn about the grouping variable", { + expect_no_warning(getLeveneTest(tse, counts ~ Geographical_location)) +}) + +test_that("getLeveneTest fails with multiple RHS vars", { + expect_error( + getLeveneTest(tse, counts ~ Geographical_location + Gender), + "exactly one" + ) +}) diff --git a/tests/testthat/test-getLm.R b/tests/testthat/test-getLm.R index 526b3c8..b23cc63 100644 --- a/tests/testthat/test-getLm.R +++ b/tests/testthat/test-getLm.R @@ -16,3 +16,72 @@ test_that("getLm allows disabling p-value adjustment", { expect_s3_class(res, "data.frame") expect_false("q_value" %in% names(res)) }) + +################################################################################ +# Mixed models +################################################################################ + +# Subjects measured at three timepoints; subset of features for speed +data(Kumaraswamy2024, package = "miaTime") +time_tse <- Kumaraswamy2024[1:10, ] +time_tse$timepoint <- factor(time_tse$timepoint) +time_tse <- mia::transformAssay( + time_tse, + assay.type = "signal", method = "rclr" +) + +test_that("getLm fits a mixed model with random effects", { + res <- getLm(time_tse, rclr ~ timepoint + (1 | subject)) + expect_s3_class(res, "data.frame") + expect_true(all(c( + "rownames", "variable", "estimate", "p_value", + "q_value" + ) %in% names(res))) + # One coefficient for each timepoint except the reference + expect_equal(nrow(res), nrow(time_tse) * 2L) + expect_false("(Intercept)" %in% res$variable) +}) + +test_that("getLm matches lmer for each feature", { + res <- getLm(time_tse, rclr ~ timepoint + (1 | subject)) + feature <- rownames(time_tse)[[1L]] + row <- res[res$rownames == feature & res$variable == "timepoint2", ] + + data_model <- data.frame( + abundance = SummarizedExperiment::assay(time_tse, "rclr")[feature, ], + timepoint = time_tse$timepoint, + subject = time_tse$subject + ) + fit <- lmerTest::lmer( + abundance ~ timepoint + (1 | subject), + data = data_model + ) + expected <- summary(fit)$coefficients["timepoint2", ] + + expect_equal(row$estimate, unname(expected["Estimate"])) + expect_equal(row$p_value, unname(expected["Pr(>|t|)"])) +}) + +test_that("getLm uses a linear model without random effects", { + res <- getLm(time_tse, rclr ~ timepoint) + feature <- rownames(time_tse)[[1L]] + row <- res[res$rownames == feature & res$variable == "timepoint2", ] + + data_model <- data.frame( + abundance = SummarizedExperiment::assay(time_tse, "rclr")[feature, ], + timepoint = time_tse$timepoint + ) + expected <- summary(lm(abundance ~ timepoint, data = data_model)) + expected <- expected$coefficients["timepoint2", ] + + expect_equal(row$estimate, unname(expected["Estimate"])) + expect_equal(row$p_value, unname(expected["Pr(>|t|)"])) +}) + +test_that("getLm allows disabling p-value adjustment of mixed models", { + res <- getLm( + time_tse, rclr ~ timepoint + (1 | subject), + p_adjust_method = NULL + ) + expect_false("q_value" %in% names(res)) +}) diff --git a/tests/testthat/test-getPermanova.R b/tests/testthat/test-getPermanova.R index 7d36dab..0e2ae0d 100644 --- a/tests/testthat/test-getPermanova.R +++ b/tests/testthat/test-getPermanova.R @@ -149,58 +149,64 @@ test_that("getPermanova fails with unknown assay or variable", { # Paired data ################################################################################ -# Two groups with the same number of samples; samples are paired by order -paired_tse <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] -paired_tse$id <- ave( - seq_len(ncol(paired_tse)), paired_tse$Geographical_location, - FUN = seq_along +# Subjects measured at several timepoints +data(Kumaraswamy2024, package = "miaTime") +time_tse <- Kumaraswamy2024 +time_tse$timepoint <- factor(time_tse$timepoint) +paired_tse <- time_tse[, time_tse$timepoint %in% c("1", "2")] + +# Samples of subjects measured at both timepoints +both_timepoints <- intersect( + paired_tse$subject[paired_tse$timepoint == "1"], + paired_tse$subject[paired_tse$timepoint == "2"] ) +complete_tse <- paired_tse[, paired_tse$subject %in% both_timepoints] test_that("getPermanova permutes within pairs with pair.by", { set.seed(1) res <- getPermanova( - paired_tse, counts ~ Geographical_location, - pairwise = TRUE, pair.by = "id" + paired_tse, signal ~ timepoint, + pairwise = TRUE, pair.by = "subject" ) - abundance <- t(SummarizedExperiment::assay(paired_tse, "counts")) + abundance <- t(SummarizedExperiment::assay(complete_tse, "signal")) set.seed(1) expected <- vegan::adonis2( vegan::vegdist(abundance, method = "bray") ~ group, data = data.frame(group = factor( - paired_tse$Geographical_location, - levels = c("Ahmednagar", "Nashik") + complete_tse$timepoint, + levels = c("1", "2") )), permutations = permute::how( - nperm = 999L, blocks = factor(paired_tse$id) + nperm = 999L, blocks = factor(complete_tse$subject) ) ) expect_equal(nrow(res), 1L) - expect_equal(res$n, ncol(paired_tse)) + expect_equal(res$n, ncol(complete_tse)) expect_equal(res$F, expected$F[[1L]]) expect_equal(res$p, expected[["Pr(>F)"]][[1L]]) }) test_that("getPermanova uses only pairs present in both groups", { - removed <- paired_tse[, -1L] + # Subjects measured at only one of the timepoints are left out + expect_lt(length(both_timepoints), length(unique(paired_tse$subject))) + set.seed(1) res <- getPermanova( - removed, counts ~ Geographical_location, - pairwise = TRUE, pair.by = "id" + paired_tse, signal ~ timepoint, + pairwise = TRUE, pair.by = "subject" ) - - # The sample without a partner is also left out - expect_equal(res$n, ncol(paired_tse) - 2L) + expect_equal(res$n, 2L * length(both_timepoints)) }) test_that("getPermanova pair.by gives different p-values than unpaired", { set.seed(1) - unpaired <- getPermanova(paired_tse, counts ~ Geographical_location) + unpaired <- getPermanova(complete_tse, signal ~ timepoint) set.seed(1) paired <- getPermanova( - paired_tse, counts ~ Geographical_location, - pair.by = "id" + complete_tse, signal ~ timepoint, + pair.by = "subject" ) # The test statistic is the same, only the permutations differ @@ -209,32 +215,33 @@ test_that("getPermanova pair.by gives different p-values than unpaired", { }) test_that("getPermanova uses only IDs present in all groups with pair.by", { - # Three groups paired by order within the group - three_groups <- tse - three_groups$id <- ave( - seq_len(ncol(three_groups)), three_groups$Geographical_location, - FUN = seq_along + # Three timepoints; subjects measured at all of them + all_timepoints <- Reduce( + intersect, + lapply(c("1", "2", "3"), function(timepoint) { + time_tse$subject[time_tse$timepoint == timepoint] + }) ) set.seed(1) res <- getPermanova( - three_groups, counts ~ Geographical_location, - pair.by = "id" + time_tse, signal ~ timepoint, + pair.by = "subject" ) - # Nashik has the fewest samples (11), so 11 IDs in each of 3 groups - expect_equal(res$n, 3L * min(table(tse$Geographical_location))) + expect_equal(res$n, 3L * length(all_timepoints)) expect_equal(nrow(res), 1L) }) test_that("getPermanova returns NA if no pairs are shared", { - # No pairing ID is present in both groups + # No pairing ID is present in both timepoints no_pairs <- paired_tse - no_pairs$id[no_pairs$Geographical_location == "Nashik"] <- - no_pairs$id[no_pairs$Geographical_location == "Nashik"] + 100L + no_pairs$subject <- paste0( + no_pairs$subject, "_", no_pairs$timepoint + ) set.seed(1) res <- getPermanova( - no_pairs, counts ~ Geographical_location, - pairwise = TRUE, pair.by = "id" + no_pairs, signal ~ timepoint, + pairwise = TRUE, pair.by = "subject" ) expect_equal(res$n, 0L) diff --git a/tests/testthat/test-getPermdisp.R b/tests/testthat/test-getPermdisp.R new file mode 100644 index 0000000..0320f0b --- /dev/null +++ b/tests/testthat/test-getPermdisp.R @@ -0,0 +1,69 @@ +# Tests for getPermdisp +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +test_that("getPermdisp returns a single test for all groups", { + set.seed(1) + res <- getPermdisp(tse, counts ~ Geographical_location) + + expect_s3_class(res, "data.frame") + expect_identical(colnames(res), c("n", "Df", "F", "p")) + expect_equal(nrow(res), 1L) + expect_equal(res$n, sum(!is.na(tse$Geographical_location))) + # Two degrees of freedom for three groups + expect_equal(res$Df, 2) +}) + +test_that("getPermdisp matches betadisper and permutest", { + set.seed(1) + res <- getPermdisp(tse, counts ~ Geographical_location) + + abundance <- t(SummarizedExperiment::assay(tse, "counts")) + set.seed(1) + fit <- vegan::betadisper( + vegan::vegdist(abundance, method = "bray"), + tse$Geographical_location + ) + expected <- vegan::permutest(fit, permutations = 999L)$tab + + expect_equal(res$F, expected$F[[1L]]) + expect_equal(res$p, expected[["Pr(>F)"]][[1L]]) +}) + +test_that("getPermdisp uses the method and permutations arguments", { + set.seed(1) + bray <- getPermdisp(tse, counts ~ Geographical_location) + set.seed(1) + euclidean <- getPermdisp( + tse, counts ~ Geographical_location, + method = "euclidean", permutations = 99L + ) + + expect_false(isTRUE(all.equal(bray$F, euclidean$F))) + # The smallest possible p-value is 1 / (permutations + 1) + expect_gte(euclidean$p, 1 / 100) +}) + +test_that("getPermdisp ignores samples with missing group", { + tse$Geographical_location[1L] <- NA + set.seed(1) + res <- getPermdisp(tse, counts ~ Geographical_location) + + expect_equal(res$n, sum(!is.na(tse$Geographical_location))) +}) + +test_that("getPermdisp requires at least two groups", { + one_group <- tse[, tse$Geographical_location == "Pune"] + expect_error( + getPermdisp(one_group, counts ~ Geographical_location), + "at least two groups" + ) +}) + +test_that("getPermdisp fails with multiple RHS vars", { + expect_error( + getPermdisp(tse, counts ~ Geographical_location + Gender), + "exactly one" + ) +}) diff --git a/tests/testthat/test-getShapiroTest.R b/tests/testthat/test-getShapiroTest.R new file mode 100644 index 0000000..a87a801 --- /dev/null +++ b/tests/testthat/test-getShapiroTest.R @@ -0,0 +1,103 @@ +# Tests for getShapiroTest +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +test_that("getShapiroTest returns one row per feature", { + res <- getShapiroTest(tse, counts ~ Geographical_location) + expect_s3_class(res, "data.frame") + expect_true(all(c("rownames", "statistic", "p", "p.adj") %in% names(res))) + expect_false(anyDuplicated(res$rownames) > 0) +}) + +test_that("getShapiroTest tests the residuals of the group model", { + res <- getShapiroTest(tse, counts ~ Geographical_location) + row <- res[res$rownames == "Firmicutes", ] + + counts <- SummarizedExperiment::assay(tse, "counts")["Firmicutes", ] + residuals <- lm(counts ~ factor(tse$Geographical_location)) |> residuals() + expected <- shapiro.test(residuals) + + expect_equal(unname(row$statistic), unname(expected$statistic)) + expect_equal(row$p, expected$p.value) +}) + +test_that("getShapiroTest does not test the values themselves", { + res <- getShapiroTest(tse, counts ~ Geographical_location) + row <- res[res$rownames == "Firmicutes", ] + + counts <- SummarizedExperiment::assay(tse, "counts")["Firmicutes", ] + values <- shapiro.test(counts) + + expect_false(isTRUE(all.equal( + unname(row$statistic), unname(values$statistic) + ))) +}) + +test_that("getShapiroTest adjusts p-values", { + res <- getShapiroTest(tse, counts ~ Geographical_location) + expect_equal(res$p.adj, stats::p.adjust(res$p, method = "BH")) + + res <- getShapiroTest( + tse, counts ~ Geographical_location, + p.adjust.method = "bonferroni" + ) + expect_equal(res$p.adj, stats::p.adjust(res$p, method = "bonferroni")) +}) + +test_that("getShapiroTest ignores missing values", { + counts <- SummarizedExperiment::assay(tse, "counts") + counts["Firmicutes", 1L] <- NA + SummarizedExperiment::assay(tse, "counts") <- counts + + res <- getShapiroTest(tse, counts ~ Geographical_location) + row <- res[res$rownames == "Firmicutes", ] + + keep <- !is.na(counts["Firmicutes", ]) + residuals <- lm( + counts["Firmicutes", keep] ~ factor(tse$Geographical_location[keep]) + ) |> residuals() + + expect_equal(row$p, shapiro.test(residuals)$p.value) +}) + +test_that("getShapiroTest skips features without variation in residuals", { + counts <- SummarizedExperiment::assay(tse, "counts") + counts["Firmicutes", ] <- 1 + SummarizedExperiment::assay(tse, "counts") <- counts + + res <- getShapiroTest(tse, counts ~ Geographical_location) + expect_false("Firmicutes" %in% res$rownames) + expect_equal(nrow(res), nrow(tse) - 1L) +}) + +test_that("getShapiroTest supports several variables", { + res <- getShapiroTest(tse, counts ~ Geographical_location + Gender) + row <- res[res$rownames == "Firmicutes", ] + + counts <- SummarizedExperiment::assay(tse, "counts")["Firmicutes", ] + residuals <- lm( + counts ~ factor(tse$Geographical_location) + factor(tse$Gender) + ) |> residuals() + + expect_equal(row$p, shapiro.test(residuals)$p.value) +}) + +# Subjects measured at several timepoints +data(Kumaraswamy2024, package = "miaTime") +paired_tse <- Kumaraswamy2024[1:10, ] +paired_tse$timepoint <- factor(paired_tse$timepoint) + +test_that("getShapiroTest supports random effects", { + res <- getShapiroTest( + paired_tse, signal ~ timepoint + (1 | subject) + ) + row <- res[res$rownames == rownames(paired_tse)[[1L]], ] + + d <- data.frame( + values = SummarizedExperiment::assay(paired_tse, "signal")[1L, ], + timepoint = paired_tse$timepoint, subject = paired_tse$subject + ) + fit <- lmerTest::lmer(values ~ timepoint + (1 | subject), data = d) + expect_equal(row$p, shapiro.test(residuals(fit))$p.value) +}) diff --git a/tests/testthat/test-getTTest.R b/tests/testthat/test-getTTest.R index 1d0ec91..5057579 100644 --- a/tests/testthat/test-getTTest.R +++ b/tests/testthat/test-getTTest.R @@ -21,3 +21,33 @@ test_that("getTTest fails with multiple RHS vars", { "exactly one" ) }) + +test_that("getTTest compares paired samples", { + # Subjects measured at two timepoints + data(Kumaraswamy2024, package = "miaTime") + paired_tse <- Kumaraswamy2024 + paired_tse$timepoint <- factor(paired_tse$timepoint) + paired_tse <- paired_tse[, paired_tse$timepoint %in% c("1", "2")] + + res <- getTTest( + paired_tse, signal ~ timepoint, + pair.by = "subject" + ) + feature <- rownames(paired_tse)[[1L]] + row <- res[res$rownames == feature, ] + + values <- SummarizedExperiment::assay(paired_tse, "signal")[feature, ] + first <- paired_tse$timepoint == "1" + second <- paired_tse$timepoint == "2" + subjects <- intersect( + paired_tse$subject[first], paired_tse$subject[second] + ) + expected <- t.test( + values[first][match(subjects, paired_tse$subject[first])], + values[second][match(subjects, paired_tse$subject[second])], + paired = TRUE + ) + + expect_equal(unname(row$statistic), unname(expected$statistic)) + expect_equal(row$p, expected$p.value) +}) diff --git a/tests/testthat/test-getTukeyTest.R b/tests/testthat/test-getTukeyTest.R new file mode 100644 index 0000000..de2aef7 --- /dev/null +++ b/tests/testthat/test-getTukeyTest.R @@ -0,0 +1,32 @@ +# Tests for getTukeyTest +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +test_that("getTukeyTest returns one row per feature and pair of groups", { + res <- getTukeyTest(tse, counts ~ Geographical_location) + expect_s3_class(res, "data.frame") + expect_true(all(c("rownames", "group1", "group2", "estimate", "p.adj") %in% + names(res))) + expect_false(anyDuplicated(paste(res$rownames, res$group1, res$group2)) > 0) +}) + +test_that("getTukeyTest matches TukeyHSD", { + res <- getTukeyTest(tse, counts ~ Geographical_location) + row <- res[res$rownames == "Firmicutes" & + res$group1 == "Ahmednagar" & res$group2 == "Nashik", ] + + counts <- SummarizedExperiment::assay(tse, "counts")["Firmicutes", ] + fit <- aov(counts ~ factor(tse$Geographical_location)) |> TukeyHSD() + expected <- fit[[1L]]["Nashik-Ahmednagar", ] + + expect_equal(row$estimate, unname(expected["diff"])) + expect_equal(row$p.adj, unname(expected["p adj"]), tolerance = 1e-3) +}) + +test_that("getTukeyTest fails with multiple RHS vars", { + expect_error( + getTukeyTest(tse, counts ~ Geographical_location + Gender), + "exactly one" + ) +}) diff --git a/tests/testthat/test-getWilcoxonTest.R b/tests/testthat/test-getWilcoxonTest.R index 5180918..ff4fc98 100644 --- a/tests/testthat/test-getWilcoxonTest.R +++ b/tests/testthat/test-getWilcoxonTest.R @@ -15,93 +15,42 @@ test_that("getWilcoxonTest with colData variable works", { expect_s3_class(res, "data.frame") }) -effect_size_columns <- c("effsize", "conf.low", "conf.high", "magnitude") - -test_that("getWilcoxonTest adds Cliff's delta by default", { - res <- getWilcoxonTest(tse, counts ~ Geographical_location) - es <- getEffectSize(tse, counts ~ Geographical_location) - merged <- merge( - as.data.frame(res)[, c("rownames", "group1", "group2", "effsize")], - es[, c("rownames", "group1", "group2", "effsize")], - by = c("rownames", "group1", "group2") - ) - - expect_true(all(effect_size_columns %in% names(res))) - expect_equal(nrow(merged), nrow(res)) - expect_equal(merged$effsize.x, merged$effsize.y) -}) - test_that("getWilcoxonTest has one row per feature and comparison", { res <- getWilcoxonTest(tse, counts ~ Geographical_location) keys <- paste(res$rownames, res$group1, res$group2) expect_false(anyDuplicated(keys) > 0L) - expect_false(any(is.na(res$effsize))) -}) - -test_that("getWilcoxonTest adds Cohen's d", { - res <- getWilcoxonTest( - tse, counts ~ Geographical_location, - effect.size = "cohen" - ) - es <- getEffectSize(tse, counts ~ Geographical_location, method = "cohen") - merged <- merge( - as.data.frame(res)[, c("rownames", "group1", "group2", "effsize")], - es[, c("rownames", "group1", "group2", "effsize")], - by = c("rownames", "group1", "group2") - ) - - expect_true(all(effect_size_columns %in% names(res))) - expect_equal(nrow(merged), nrow(res)) - expect_equal(merged$effsize.x, merged$effsize.y) -}) - -test_that("getWilcoxonTest rejects unknown effect sizes", { - expect_error( - getWilcoxonTest(tse, counts ~ Geographical_location, - effect.size = "other" - ), - "should be one of" - ) }) ################################################################################ # Paired tests ################################################################################ -paired_tse <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] -paired_tse$id <- ave( - seq_len(ncol(paired_tse)), paired_tse$Geographical_location, - FUN = seq_along -) +# Subjects measured at several timepoints +data(Kumaraswamy2024, package = "miaTime") +time_tse <- Kumaraswamy2024 +time_tse$timepoint <- factor(time_tse$timepoint) +paired_tse <- time_tse[, time_tse$timepoint %in% c("1", "2")] -test_that("getWilcoxonTest warns and skips paired Cliff's delta", { - expect_warning( - res <- getWilcoxonTest( - paired_tse, counts ~ Geographical_location, - pair.by = "id" - ), - "Paired Cliff's delta is not supported" - ) - expect_true("p" %in% names(res)) - expect_false(any(effect_size_columns %in% names(res))) -}) - -test_that("getWilcoxonTest adds paired Cohen's d", { +test_that("getWilcoxonTest compares paired samples", { res <- getWilcoxonTest( - paired_tse, counts ~ Geographical_location, - pair.by = "id", effect.size = "cohen" + paired_tse, signal ~ timepoint, + pair.by = "subject" ) - es <- getEffectSize( - paired_tse, counts ~ Geographical_location, - method = "cohen", pair.by = "id" + feature <- rownames(paired_tse)[[1L]] + row <- res[res$rownames == feature, ] + + values <- SummarizedExperiment::assay(paired_tse, "signal")[feature, ] + first <- paired_tse$timepoint == "1" + second <- paired_tse$timepoint == "2" + subjects <- intersect( + paired_tse$subject[first], paired_tse$subject[second] ) - merged <- merge( - as.data.frame(res)[, c("rownames", "group1", "group2", "effsize")], - es[, c("rownames", "group1", "group2", "effsize")], - by = c("rownames", "group1", "group2") + expected <- wilcox.test( + values[first][match(subjects, paired_tse$subject[first])], + values[second][match(subjects, paired_tse$subject[second])], + paired = TRUE ) - expect_true(all(effect_size_columns %in% names(res))) - expect_equal(merged$effsize.x, merged$effsize.y) + expect_equal(row$p, expected$p.value) }) diff --git a/vignettes/daa.Rmd b/vignettes/daa.Rmd index ef59e8d..630a3f7 100644 --- a/vignettes/daa.Rmd +++ b/vignettes/daa.Rmd @@ -33,71 +33,392 @@ if (!requireNamespace("BiocManager", quietly = TRUE)) { BiocManager::install("daa") ``` -# Available Methods +# Example data -## Wilcoxon rank-sum test - -The `getWilcoxonTest()` function performs nonparametric Wilcoxon rank-sum tests -for each feature, comparing two groups. - -```{r wilcoxon, message = FALSE} +```{r setup-data, message = FALSE} library(daa) library(mia) -# Load example data +# Cross-sectional data with three groups data(peerj13075, package = "mia") tse <- peerj13075 - -# Agglomerate to phylum level tse <- agglomerateByRank(tse, "phylum") +tse <- addAlpha(tse, index = "shannon") +``` -# Run Wilcoxon test -res <- getWilcoxonTest(tse, counts ~ Geographical_location) -head(res) +Paired examples use `miaTime` data, where subjects are measured at three +timepoints. + +```{r paired-data} +data(Kumaraswamy2024, package = "miaTime") +tse_time <- Kumaraswamy2024 +tse_time$timepoint <- factor(tse_time$timepoint) ``` -## t-test +# Do feature abundances differ between groups? {#differences} + +The map shows the workflow for comparing independent groups. Follow the arrows +from top to bottom. Blue boxes are decisions and green boxes name the function +to use. + +```{r map-groups, echo = FALSE, fig.cap = "Workflow for independent groups.", out.width = "100%"} +DiagrammeR::grViz(" +digraph map_groups { + graph [rankdir = TB, nodesep = 0.25, ranksep = 0.45, fontname = Helvetica, + fontsize = 15, labeljust = l, style = 'rounded,dashed', color = gray60] + node [shape = box, style = 'rounded,filled', fontname = Helvetica, + fontsize = 16, margin = '0.15,0.08', fillcolor = '#dbe9f6', + color = '#4a7fb5'] + edge [color = gray50, arrowsize = 0.7, fontname = Helvetica, fontsize = 13] + + Q [label = 'Do abundances differ between\\nindependent groups?', shape = oval] + + TM [label = 'Testing or modeling?'] + CK [label = 'Can the residuals be\\nassumed normal?'] + GY [label = 'Number of\\ngroups'] + GN [label = 'Number of\\ngroups'] + TT [label = 'getTTest()', fillcolor = '#dff0d8', color = '#5b9a4a'] + AN [label = 'getAnova()', fillcolor = '#dff0d8', color = '#5b9a4a'] + WI [label = 'getWilcoxonTest()', fillcolor = '#dff0d8', color = '#5b9a4a'] + KR [label = 'getKruskal()', fillcolor = '#dff0d8', color = '#5b9a4a'] + + subgraph cluster3 { label = 'Which groups differ?'; + TK [label = 'getTukeyTest()', fillcolor = '#dff0d8', color = '#5b9a4a'] + DU [label = 'getDunnTest()', fillcolor = '#dff0d8', color = '#5b9a4a'] } + + subgraph cluster4 { label = 'Effect size (separate step)'; + ES [label = 'getEffectSize()', fillcolor = '#dff0d8', color = '#5b9a4a'] } + + AD [label = 'Adjust covariates?'] + ML [label = 'getLm(), getLimma()', fillcolor = '#dff0d8', color = '#5b9a4a'] + MO [label = 'getGlm(), getOrm()', fillcolor = '#dff0d8', color = '#5b9a4a'] + + Q -> TM + TM -> CK [label = ' test groups'] + CK -> GY [label = ' yes'] + CK -> GN [label = ' no'] + GY -> TT [label = ' two'] + GY -> AN [label = ' 3+'] + GN -> WI [label = ' two'] + GN -> KR [label = ' 3+'] + AN -> TK + KR -> DU + TT -> ES [style = dotted] + WI -> ES [style = dotted] + TM -> AD [label = ' model: covariates,\\nrandom effects,\\ndistribution', style = dashed] + AD -> ML [label = ' normal residuals', style = dashed] + AD -> MO [label = ' other', style = dashed] +} +", width = "100%", height = 700) +``` -The `getTTest()` function performs t-tests (Welch's by default). +Choose between parametric and nonparametric tests based on what you can +assume about the data. The t-test and ANOVA assume that the **residuals**, i.e., +the differences between the values and the group means, are normally +distributed. If you cannot assume this, use the nonparametric tests. + +## Compare the groups + +### Two groups + +Parametric: the `getTTest()` function performs t-tests for each feature +(Welch's by default). ```{r ttest} res <- getTTest(tse, counts ~ Geographical_location) head(res) ``` -## ANOVA and Kruskal-Wallis +Nonparametric: the `getWilcoxonTest()` function performs Wilcoxon rank-sum +tests. If the grouping variable has more than two groups, all pairs of groups +are compared. + +```{r wilcoxon} +res <- getWilcoxonTest(tse, counts ~ Geographical_location) +head(res) +``` -For comparing more than two groups: +The effect size is a separate step. `getEffectSize()` calculates, e.g., +Cliff's delta, Cohen's d, or the difference, ratio or log2 ratio (log fold +change) of the group means. + +```{r effectsize} +es <- getEffectSize(tse, counts ~ Geographical_location) +head(es) +``` + +### Three or more groups + +These tests tell only whether some of the groups differ. The post-hoc test that +follows each of them tells which groups differ, by comparing all pairs. + +**Parametric:** ANOVA, followed by Tukey's test. ```{r anova} res <- getAnova(tse, counts ~ Geographical_location) head(res) ``` +```{r tukey} +res <- getTukeyTest(tse, counts ~ Geographical_location) +head(res) +``` + +**Nonparametric:** the Kruskal-Wallis test, followed by Dunn's test. + ```{r kruskal} res <- getKruskal(tse, counts ~ Geographical_location) head(res) ``` +```{r dunn} +res <- getDunnTest(tse, counts ~ Geographical_location) +head(res) +``` + +## With covariates {#covariates} + +To adjust for covariates, fit a model per feature and test the variable of +interest. Covariates are not the only reason to use a model instead of a test: + +- **Random effects** for repeated measurements, with `getLm()`. +- **Few samples and many features:** `getLimma()` borrows information across + features to stabilize the variance estimates. +- **Distribution of the data:** counts, overdispersion, binary or positive + values are modeled with a suitable family in `getGlm()`. +- **Ordinal or skewed data:** `getOrm()` does not assume normal residuals. + +If the residuals can be assumed to be normal, use `getLm()` or `getLimma()`. +If not, use a model that does not assume normality: `getGlm()` fits a +generalized linear model with a distribution suitable for the data, and +`getOrm()` fits an ordinal regression. The formula has the assay name on the +LHS. For presence, use `getFirth()` (see [below](#presence)). + +```{r lm, eval = FALSE} +# Linear model per feature +tse <- transformAssay(tse, method = "rclr") +res <- getLm(tse, rclr ~ Geographical_location + Gender) + +# Limma +fit <- getLimma(tse, counts ~ Geographical_location + Gender) + +# Ordinal regression +res <- getOrm(tse, counts ~ Geographical_location + Gender) +``` + +The likelihood of `getGlm()` is chosen with `family`. For example, a Poisson +model is suitable for counts, and a negative binomial model (`"negbin"`) for +overdispersed counts, which is common in microbiome data. The estimates are on +the scale of the link function, i.e., the log scale for these models. + +```{r glm, warning = FALSE} +# Poisson model for counts +res <- getGlm(tse, counts ~ Geographical_location + Gender) +head(res) + +# Negative binomial model for overdispersed counts +res <- getGlm( + tse, counts ~ Geographical_location + Gender, + family = "negbin" +) +head(res) +``` + +Counts depend on the sequencing depth of the sample. To model the abundance +relative to it, give the log of the library size as an `offset`, either as a +column of `colData` or as a vector. + +```{r glm-offset, warning = FALSE} +tse$log_total <- log(colSums(assay(tse, "counts"))) +res <- getGlm( + tse, counts ~ Geographical_location + Gender, + family = "negbin", + offset = "log_total" +) +head(res) +``` + +Other families are also possible, e.g., `binomial()` for presence (logistic +regression), `Gamma(link = "log")` for positive continuous values, and +`gaussian()`, which is the same as `getLm()`. + ## Testing metadata variables You can also test variables from `colData`. For example, testing alpha diversity indices: ```{r metadata} -# Add alpha diversity to colData -tse <- mia::addAlpha(tse, index = "shannon") - -# Test diversity differences between groups res <- getWilcoxonTest(tse, shannon ~ Geographical_location) head(res) ``` -## PERMANOVA +# Do paired or repeated measurements differ? {#paired-and-repeated-measurements} + +For paired samples, e.g., repeated measurements from the same subject, give the +column that identifies the pairs with `pair.by`. Only subjects present in all +compared groups are used. In `tse_time`, the samples of the same subject are +paired by `subject`. + +```{r map-paired, echo = FALSE, fig.cap = "Workflow for paired or repeated measurements.", out.width = "100%"} +DiagrammeR::grViz(" +digraph map_paired { + graph [rankdir = TB, nodesep = 0.25, ranksep = 0.45, fontname = Helvetica, + fontsize = 15, labeljust = l, style = 'rounded,dashed', color = gray60] + node [shape = box, style = 'rounded,filled', fontname = Helvetica, + fontsize = 16, margin = '0.15,0.08', fillcolor = '#dbe9f6', + color = '#4a7fb5'] + edge [color = gray50, arrowsize = 0.7, fontname = Helvetica, fontsize = 13] + + Q [label = 'Do paired or repeated\\nmeasurements differ?', shape = oval] + + G [label = 'Number of\\ngroups'] + PT [label = 'getTTest() or\\ngetWilcoxonTest()', fillcolor = '#dff0d8', color = '#5b9a4a'] + FR [label = 'getFriedmanTest()', fillcolor = '#dff0d8', color = '#5b9a4a'] + + LM [label = 'To adjust for covariates:\\ngetLm() with a random effect', fillcolor = '#dff0d8', color = '#5b9a4a'] + + Q -> G + G -> PT [label = ' two'] + G -> FR [label = ' 2+'] + Q -> LM [style = dashed] +} +", width = "100%", height = 420) +``` + +## Compare the groups + +Two timepoints are compared with a paired t-test or Wilcoxon test, and two or +more with the Friedman test. Here, there are three timepoints. + +For two timepoints, use `getTTest()` or `getWilcoxonTest()` with `pair.by`. +The effect size is calculated separately with `getEffectSize()`; paired +Cliff's delta is not supported, so use, e.g., Cohen's d. + +```{r paired-wilcoxon} +tse_pair <- tse_time[, tse_time$timepoint %in% c("1", "2")] +res <- getWilcoxonTest( + tse_pair, signal ~ timepoint, + pair.by = "subject" +) +head(res) +``` + +The Friedman test compares two or more paired groups, here all three +timepoints. + +```{r friedman} +res <- getFriedmanTest(tse_time, signal ~ timepoint, pair.by = "subject") +head(res) +``` + +## With covariates + +Add a random effect for the subject to the formula of `getLm()`, e.g., +`(1 | subject)`, to fit a linear mixed model that can also have covariates. + +```{r lm-mixed, eval = FALSE} +tse_time <- transformAssay(tse_time, assay.type = "signal", method = "rclr") +res <- getLm(tse_time, rclr ~ timepoint + (1 | subject)) +``` + +# Is a feature present more often in some groups? {#presence} + +If you are interested in whether a feature is detected rather than in its +abundance, test the presence of the feature. A feature is present in a sample +if its value is higher than `detection` (0 by default). + +```{r map-presence, echo = FALSE, fig.cap = "Workflow for presence.", out.width = "100%"} +DiagrammeR::grViz(" +digraph map_presence { + graph [rankdir = TB, nodesep = 0.25, ranksep = 0.45, fontname = Helvetica, + fontsize = 15, labeljust = l, style = 'rounded,dashed', color = gray60] + node [shape = box, style = 'rounded,filled', fontname = Helvetica, + fontsize = 16, margin = '0.15,0.08', fillcolor = '#dbe9f6', + color = '#4a7fb5'] + edge [color = gray50, arrowsize = 0.7, fontname = Helvetica, fontsize = 13] + + Q [label = 'Is a feature present more often\\nin some groups?', shape = oval] + + S [label = 'Number of\\nsamples'] + FI [label = 'getFisherTest()', fillcolor = '#dff0d8', color = '#5b9a4a'] + CH [label = 'getChisqTest()', fillcolor = '#dff0d8', color = '#5b9a4a'] + + LR [label = 'To adjust for covariates:\\ngetFirth() (logistic regression)', fillcolor = '#dff0d8', color = '#5b9a4a'] + + Q -> S + S -> FI [label = ' few'] + S -> CH [label = ' many'] + Q -> LR [style = dashed] +} +", width = "100%", height = 420) +``` + +## Test the presence + +Fisher's exact test is suitable also when there are few samples. The chi-square +test is an approximation that needs more samples. + +```{r fisher} +res <- getFisherTest(tse, counts ~ Geographical_location) +head(res) +``` + +```{r chisq, warning = FALSE} +res <- getChisqTest(tse, counts ~ Geographical_location) +head(res) +``` + +## With covariates + +The tests above cannot adjust for covariates. Logistic regression of the +presence of the feature can. `getFirth()` fits a logistic regression with +Firth's correction per feature, which also works when a feature is present +in all or none of the samples of a group. The LHS is a binary assay, here +presence (`"pa"`), and the RHS can have covariates. + +```{r firth, warning = FALSE} +tse <- transformAssay(tse, assay.type = "counts", method = "pa") +res <- getFirth(tse, pa ~ Geographical_location + Gender) +head(res) +``` + +# Does the overall composition differ between groups? {#composition} The `getPermanova()` function compares the overall composition between groups -with a single test. The p-values are based on permutations, so a seed is set -for reproducibility. +with a single test, instead of testing each feature separately. The p-values are +based on permutations, so a seed is set for reproducibility. + +```{r map-composition, echo = FALSE, fig.cap = "Workflow for composition.", out.width = "100%"} +DiagrammeR::grViz(" +digraph map_composition { + graph [rankdir = TB, nodesep = 0.25, ranksep = 0.45, fontname = Helvetica, + fontsize = 15, labeljust = l, style = 'rounded,dashed', color = gray60] + node [shape = box, style = 'rounded,filled', fontname = Helvetica, + fontsize = 16, margin = '0.15,0.08', fillcolor = '#dbe9f6', + color = '#4a7fb5'] + edge [color = gray50, arrowsize = 0.7, fontname = Helvetica, fontsize = 13] + + Q [label = 'Does the overall composition\\ndiffer between groups?', shape = oval] + + D [label = 'All groups at once or\\neach pair of groups?'] + PM [label = 'getPermanova()', fillcolor = '#dff0d8', color = '#5b9a4a'] + PW [label = 'getPermanova()\\nwith pairwise = TRUE', fillcolor = '#dff0d8', color = '#5b9a4a'] + + subgraph cluster2 { label = 'Check the dispersion'; + PD [label = 'getPermdisp()', fillcolor = '#dff0d8', color = '#5b9a4a'] } + + Q -> D + D -> PM [label = ' all at once'] + D -> PW [label = ' each pair'] + PM -> PD + PW -> PD +} +", width = "100%", height = 520) +``` + +## Test the composition + +### All groups at once ```{r permanova} set.seed(1) @@ -105,43 +426,94 @@ res <- getPermanova(tse, counts ~ Geographical_location) res ``` -To compare each pair of groups, use `pairwise = TRUE`. For paired samples, use -`pair.by` to permute the group labels only within pairs. +### Each pair of groups + +Instead of one test for all groups, use `pairwise = TRUE` to compare each pair +of groups. For paired samples, use `pair.by` to permute the group labels only +within pairs. ```{r permanova-pairwise} set.seed(1) res <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) res +``` + +For example, to compare the three timepoints with the samples paired by subject: + +```{r permanova-paired} +set.seed(1) +res <- getPermanova(tse_time, signal ~ timepoint, pair.by = "subject") +res +``` + +## Check the dispersion + +PERMANOVA is also sensitive to differences in the spread of the samples within +groups. Use `getPermdisp()` to test whether the groups differ in dispersion. If +they do, a significant PERMANOVA may be due to the dispersion and not to a +difference in the location of the groups. + +```{r permdisp} +set.seed(1) +res <- getPermdisp(tse, counts ~ Geographical_location) +res +``` -## Correlation +# Is a feature associated with a numeric variable? {#association} The `getCorrelationTest()` function tests the correlation between feature values and a numeric variable (Spearman by default). +```{r map-association, echo = FALSE, fig.cap = "Workflow for association with a numeric variable.", out.width = "100%"} +DiagrammeR::grViz(" +digraph map_association { + graph [rankdir = TB, nodesep = 0.25, ranksep = 0.45, fontname = Helvetica, + fontsize = 15, labeljust = l, style = 'rounded,dashed', color = gray60] + node [shape = box, style = 'rounded,filled', fontname = Helvetica, + fontsize = 16, margin = '0.15,0.08', fillcolor = '#dbe9f6', + color = '#4a7fb5'] + edge [color = gray50, arrowsize = 0.7, fontname = Helvetica, fontsize = 13] + + Q [label = 'Is a feature associated with\\na numeric variable?', shape = oval] + D [label = 'Adjust for\\ncovariates?'] + + CO [label = 'getCorrelationTest()', fillcolor = '#dff0d8', color = '#5b9a4a'] + CA [label = 'getCorrelationTest()\\nwith adjust.by', fillcolor = '#dff0d8', color = '#5b9a4a'] + + Q -> D + D -> CO [label = ' no'] + D -> CA [label = ' yes'] +} +", width = "100%", height = 380) +``` + +## Without covariates + ```{r correlation} res <- getCorrelationTest(tse, counts ~ shannon) head(res) ``` +## With covariates + To remove the effect of covariates before testing, use `adjust.by`. Both -variables are regressed on the covariates and the residuals are correlated. +variables are regressed on the covariates and the residuals are correlated. For +Spearman correlation, the variables are ranked first, which gives the partial +Spearman correlation. Kendall correlation is not supported with `adjust.by`. ```{r correlation-adjusted} res <- getCorrelationTest(tse, counts ~ shannon, adjust.by = "Gender") head(res) ``` -## Wide-format methods - -For model-based approaches, use formula with the assay name on the LHS: - -```{r lm, eval = FALSE} -# Linear model per feature -tse <- transformAssay(tse, method = "rclr") -res <- getLm(tse, rclr ~ Geographical_location) +For repeated measurements, `adjust.by` can be a formula with random effects. The +residuals of a linear mixed model are then correlated. -# Limma -fit <- getLimma(tse, counts ~ Geographical_location) +```{r correlation-mixed, eval = FALSE} +res <- getCorrelationTest( + tse_time, signal ~ numeric_variable, + adjust.by = ~ sex + (1 | subject) +) ``` # Session Info