From c5fb5a47bbd949ffbbef270aef7f485f0ce6d523 Mon Sep 17 00:00:00 2001 From: Tuomas Borman Date: Tue, 1 Dec 2026 11:00:07 +0200 Subject: [PATCH 1/2] Add permanova --- DESCRIPTION | 4 +- NAMESPACE | 6 + R/getEffectSize.R | 22 --- R/getPermanova.R | 209 ++++++++++++++++++++++++ R/getWilcoxonTest.R | 7 +- R/utils.R | 44 ++++- man/getPermanova.Rd | 84 ++++++++++ man/getWilcoxonTest.Rd | 15 +- tests/testthat/test-getPermanova.R | 249 +++++++++++++++++++++++++++++ vignettes/daa.Rmd | 21 +++ 10 files changed, 624 insertions(+), 37 deletions(-) create mode 100644 R/getPermanova.R create mode 100644 man/getPermanova.Rd create mode 100644 tests/testthat/test-getPermanova.R diff --git a/DESCRIPTION b/DESCRIPTION index 7d41e26..56d6fb8 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -25,12 +25,14 @@ Imports: effsize, limma, logistf, + permute, rlang, rms, rstatix, stats, tidyr, - utils + utils, + vegan Suggests: mia, BiocStyle, diff --git a/NAMESPACE b/NAMESPACE index 74d1adb..b0670aa 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -7,6 +7,7 @@ export(getKruskal) export(getLimma) export(getLm) export(getOrm) +export(getPermanova) export(getTTest) export(getWilcoxonTest) importFrom(SummarizedExperiment, @@ -38,6 +39,7 @@ importFrom(logistf, logistf, logistf.control ) +importFrom(permute,how) importFrom(rlang, "!!", .data, @@ -63,3 +65,7 @@ importFrom(stats, ) importFrom(tidyr,pivot_longer) importFrom(utils,combn) +importFrom(vegan, + adonis2, + vegdist +) diff --git a/R/getEffectSize.R b/R/getEffectSize.R index 4044371..5928378 100644 --- a/R/getEffectSize.R +++ b/R/getEffectSize.R @@ -85,28 +85,6 @@ getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), return(results) } -#' Get all pairwise combinations of groups, e.g., A-B, A-C, B-C -#' -#' The order of groups sets which group is group1 and group2, and matches the -#' order used by rstatix. -#' -#' @keywords internal -#' @noRd -#' @importFrom utils combn -.get_group_pairs <- function(df, group_column) { - group_names <- if (is.factor(df[[group_column]])) { - levels(droplevels(df[[group_column]])) - } else { - sort(unique(df[[group_column]])) - } - if (length(group_names) < 2L) { - stop("'", group_column, "' must have at least two groups.", - call. = FALSE - ) - } - combn(as.character(group_names), 2L, simplify = FALSE) -} - #' Calculate effect size for one feature and one pair of groups #' #' @return A one-row \code{data.frame}. diff --git a/R/getPermanova.R b/R/getPermanova.R new file mode 100644 index 0000000..27b7ce4 --- /dev/null +++ b/R/getPermanova.R @@ -0,0 +1,209 @@ +#' @title Perform PERMANOVA +#' +#' @description +#' Performs permutational multivariate analysis of variance (PERMANOVA) to +#' compare the overall composition between groups. +#' +#' @details +#' A distance matrix between samples is calculated from the assay with +#' \code{\link[vegan:vegdist]{vegan::vegdist}} and groups are compared with +#' \code{\link[vegan:adonis2]{vegan::adonis2}}. +#' +#' By default, a single PERMANOVA tests whether any of the groups differ. With +#' \code{pairwise = TRUE}, PERMANOVA is performed for each pair of groups, and +#' the p-values are adjusted for the number of comparisons and added to column +#' \code{p.adj}. +#' +#' If \code{pair.by} is given, samples are paired by that column, e.g., repeated +#' measurements from the same subject. Only pairing IDs present in all compared +#' groups are used, and the group labels are permuted only within each pairing +#' ID, so that the pairing is kept in the test. +#' +#' The p-values are 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 pairwise \code{Logical scalar}. Whether to test each pair of groups +#' separately instead of all groups at once. (Default: \code{FALSE}) +#' @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 p.adjust.method \code{Character scalar}. Method passed to +#' \code{p.adjust} for multiple testing correction of pairwise comparisons. +#' (Default: \code{"BH"}) +#' @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{adonis2}. +#' +#' @return A \code{data.frame} with columns \code{n}, \code{Df}, \code{R2}, +#' \code{F} and \code{p}. With \code{pairwise = TRUE}, there is one row per +#' pair of groups with additional columns \code{group1}, \code{group2} and +#' \code{p.adj}. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' set.seed(20261201) +#' res <- getPermanova(tse, counts ~ Geographical_location) +#' +#' # Compare each pair of groups +#' res <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) +#' +#' @seealso +#' \code{\link[vegan:adonis2]{vegan::adonis2}} +#' +#' @export +getPermanova <- function( + tse, formula, pairwise = FALSE, method = "bray", permutations = 999L, + p.adjust.method = "BH", pair.by = NULL, ...) { + if (length(all.vars(formula[[3]])) != 1L) { + stop("Formula RHS must specify exactly one grouping variable.", + call. = FALSE + ) + } + group_column <- .get_rhs(formula) + # Assay (features x samples) and sample metadata with the grouping + # variable and the pairing variable + data_list <- .get_wide_data(tse, formula, pair.by) + # Samples as rows, as required by vegdist + abundance <- data_list[["matrix"]] |> t() + sample_data <- data_list[["sample_metadata"]] + # Samples without a group (or pairing ID) cannot be used + has_values <- stats::complete.cases(sample_data) + abundance <- abundance[has_values, , drop = FALSE] + sample_data <- sample_data[has_values, , drop = FALSE] + if (pairwise) { + # One PERMANOVA for each pair of groups + res <- .calculate_pairwise_permanova( + abundance, sample_data, group_column, method, permutations, + p.adjust.method, pair.by, ... + ) + } else { + # One PERMANOVA for all groups at once + group_names <- .get_group_names(sample_data, group_column) + res <- .calculate_permanova( + abundance, sample_data, group_names, group_column, method, + permutations, pair.by, ... + ) + } + return(res) +} + +#' Run PERMANOVA for each pair of groups +#' +#' @return A \code{data.frame} with one row per pair of groups. +#' +#' @keywords internal +#' @noRd +.calculate_pairwise_permanova <- function( + abundance, sample_data, group_column, method, permutations, + p.adjust.method, pair.by, ...) { + # All pairwise combinations of groups, e.g., A-B, A-C, B-C + group_pairs <- .get_group_pairs(sample_data, group_column) + results <- lapply(group_pairs, function(group_pair) { + # PERMANOVA using only the samples of the two groups + res <- .calculate_permanova( + abundance, sample_data, group_pair, group_column, method, + permutations, pair.by, ... + ) + # Add the compared groups to the result + cbind(group1 = group_pair[[1L]], group2 = group_pair[[2L]], res) + }) + results <- do.call(rbind, results) + # Adjust p-values for the number of comparisons + results[["p.adj"]] <- stats::p.adjust(results[["p"]], p.adjust.method) + return(results) +} + +#' Run PERMANOVA for a set of groups +#' +#' @return A one-row \code{data.frame}. +#' +#' @keywords internal +#' @noRd +#' @importFrom vegan adonis2 vegdist +.calculate_permanova <- function( + abundance, sample_data, groups, group_column, method, permutations, + pair.by, ...) { + # Samples that belong to the compared groups (and have a partner in all + # groups if the samples are paired) + in_groups <- .select_samples(sample_data, groups, group_column, pair.by) + # Grouping variable for adonis2; the order of levels is the order of groups + group_data <- data.frame( + group = factor(sample_data[[group_column]][in_groups], levels = groups) + ) + # Default result is NA if a group has no samples or there are too few + # samples, because the test cannot be calculated + results <- data.frame( + n = nrow(group_data), Df = NA_real_, R2 = NA_real_, F = NA_real_, + p = NA_real_ + ) + if (nrow(group_data) < 3L || any(table(group_data[["group"]]) == 0L)) { + return(results) + } + # Distances are calculated between the samples of the compared groups + group_distances <- vegdist(abundance[in_groups, , drop = FALSE], method) + # Permutation test; with pairing, labels are permuted within pairs only + fit <- adonis2( + group_distances ~ group, + data = group_data, + permutations = .get_permutation_scheme( + pair.by, sample_data, in_groups, permutations + ), + ... + ) + # The first row of the adonis2 table is the grouping variable + results[["Df"]] <- fit[["Df"]][[1L]] + results[["R2"]] <- fit[["R2"]][[1L]] + results[["F"]] <- fit[["F"]][[1L]] + results[["p"]] <- fit[["Pr(>F)"]][[1L]] + return(results) +} + +#' Select samples that belong to the compared groups +#' +#' With pairing, only pairing IDs present in all groups can be compared. +#' +#' @return A logical vector. +#' +#' @keywords internal +#' @noRd +.select_samples <- function(sample_data, groups, group_column, pair.by) { + in_groups <- sample_data[[group_column]] %in% groups + if (is.null(pair.by)) { + return(in_groups) + } + ids <- sample_data[[pair.by]] + # Pairing IDs that are found in every compared group + shared_ids <- Reduce( + intersect, + lapply(groups, function(group) { + ids[sample_data[[group_column]] %in% group] + }) + ) + # Remove samples whose pairing ID is not found in all groups + in_groups & ids %in% shared_ids +} + +#' Get permutation scheme +#' +#' Without pairing IDs, labels are permuted freely. With pairing IDs, labels +#' are permuted only within each pairing ID. +#' +#' @keywords internal +#' @noRd +#' @importFrom permute how +.get_permutation_scheme <- function( + pair.by, sample_data, in_groups, permutations) { + if (is.null(pair.by)) { + return(how(nperm = permutations)) + } + # Blocks restrict permutations: labels are shuffled only within a block + pairing_ids <- sample_data[[pair.by]][in_groups] + how(nperm = permutations, blocks = factor(pairing_ids)) +} diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index 73fdb48..047e6e5 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -16,12 +16,12 @@ #' @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 pair.by \code{Character scalar} or \code{NULL}. Column for pairing -#' samples in paired tests. (Default: \code{NULL}) #' @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. @@ -41,7 +41,8 @@ #' @importFrom rstatix wilcox_test #' @importFrom dplyr left_join #' @export -getWilcoxonTest <- function(tse, formula, pair.by = NULL, effect.size = c("cliff", "cohen"), ...) { +getWilcoxonTest <- function( + tse, formula, effect.size = c("cliff", "cohen"), pair.by = NULL, ...) { effect.size <- match.arg(effect.size) if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", diff --git a/R/utils.R b/R/utils.R index eb157d4..8f7faa2 100644 --- a/R/utils.R +++ b/R/utils.R @@ -122,6 +122,42 @@ return(df) } +################################################################################ +# Group helpers +################################################################################ + +#' Get group names +#' +#' The order of groups sets which group is group1 and group2, and matches the +#' order used by rstatix. +#' +#' @keywords internal +#' @noRd +.get_group_names <- function(df, group_column) { + groups <- df[[group_column]] + group_names <- if (is.factor(groups)) { + groups |> droplevels() |> levels() + } else { + groups |> unique() |> sort() + } + if (length(group_names) < 2L) { + stop("'", group_column, "' must have at least two groups.", + call. = FALSE + ) + } + group_names |> as.character() +} + +#' Get all pairwise combinations of groups, e.g., A-B, A-C, B-C +#' +#' @keywords internal +#' @noRd +#' @importFrom utils combn +.get_group_pairs <- function(df, group_column) { + .get_group_names(df, group_column) |> + combn(2L, simplify = FALSE) +} + ################################################################################ # Rstatix calculator ################################################################################ @@ -184,7 +220,7 @@ #' @keywords internal #' @noRd #' @importFrom SummarizedExperiment assay colData assayNames -.get_wide_data <- function(tse, formula) { +.get_wide_data <- function(tse, formula, pair.by = NULL) { lhs <- .get_lhs(formula) rhs <- .get_rhs(formula) @@ -197,6 +233,10 @@ call. = FALSE ) } + # Pairing variable is a sample variable + if (!all(pair.by %in% colnames(colData(tse)))) { + stop("'pair.by' must be a column in colData(x).", call. = FALSE) + } is_assay <- lhs %in% assayNames(tse) if (is_assay) { @@ -208,7 +248,7 @@ } lhs_df <- lhs_df |> as.data.frame() - rhs_df <- colData(tse)[, rhs, drop = FALSE] |> + rhs_df <- colData(tse)[, c(rhs, pair.by), drop = FALSE] |> as.data.frame() if (!all(vapply(lhs_df, is.numeric, logical(1L)))) { diff --git a/man/getPermanova.Rd b/man/getPermanova.Rd new file mode 100644 index 0000000..4100449 --- /dev/null +++ b/man/getPermanova.Rd @@ -0,0 +1,84 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getPermanova.R +\name{getPermanova} +\alias{getPermanova} +\title{Perform PERMANOVA} +\usage{ +getPermanova( + tse, + formula, + pairwise = FALSE, + method = "bray", + permutations = 999L, + p.adjust.method = "BH", + pair.by = NULL, + ... +) +} +\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{pairwise}{\code{Logical scalar}. Whether to test each pair of groups +separately instead of all groups at once. (Default: \code{FALSE})} + +\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{p.adjust.method}{\code{Character scalar}. Method passed to +\code{p.adjust} for multiple testing correction of pairwise comparisons. +(Default: \code{"BH"})} + +\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{adonis2}.} +} +\value{ +A \code{data.frame} with columns \code{n}, \code{Df}, \code{R2}, +\code{F} and \code{p}. With \code{pairwise = TRUE}, there is one row per +pair of groups with additional columns \code{group1}, \code{group2} and +\code{p.adj}. +} +\description{ +Performs permutational multivariate analysis of variance (PERMANOVA) to +compare the overall composition between groups. +} +\details{ +A distance matrix between samples is calculated from the assay with +\code{\link[vegan:vegdist]{vegan::vegdist}} and groups are compared with +\code{\link[vegan:adonis2]{vegan::adonis2}}. + +By default, a single PERMANOVA tests whether any of the groups differ. With +\code{pairwise = TRUE}, PERMANOVA is performed for each pair of groups, and +the p-values are adjusted for the number of comparisons and added to column +\code{p.adj}. + +If \code{pair.by} is given, samples are paired by that column, e.g., repeated +measurements from the same subject. Only pairing IDs present in all compared +groups are used, and the group labels are permuted only within each pairing +ID, so that the pairing is kept in the test. + +The p-values are based on permutations, so set a seed for reproducible +results. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +set.seed(20261201) +res <- getPermanova(tse, counts ~ Geographical_location) + +# Compare each pair of groups +res <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) + +} +\seealso{ +\code{\link[vegan:adonis2]{vegan::adonis2}} +} diff --git a/man/getWilcoxonTest.Rd b/man/getWilcoxonTest.Rd index 136d81b..e5983de 100644 --- a/man/getWilcoxonTest.Rd +++ b/man/getWilcoxonTest.Rd @@ -7,8 +7,8 @@ getWilcoxonTest( tse, formula, - pair.by = NULL, effect.size = c("cliff", "cohen"), + pair.by = NULL, ... ) } @@ -19,14 +19,14 @@ getWilcoxonTest( (assay name, colData, or rowData variable) and the RHS specifies the grouping variable, e.g., \code{counts ~ Group}.} -\item{pair.by}{\code{Character scalar} or \code{NULL}. Column for pairing -samples in paired tests. (Default: \code{NULL})} - \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{ @@ -39,13 +39,10 @@ two groups. An effect size is added to the results. \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 and -p-values are adjusted. +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, so with \code{pair.by} use -\code{effect.size = "cohen"}; otherwise a warning is given and no effect -size is added. +Paired Cliff's delta is not supported. } \examples{ data(peerj13075, package = "mia") diff --git a/tests/testthat/test-getPermanova.R b/tests/testthat/test-getPermanova.R new file mode 100644 index 0000000..331cdc2 --- /dev/null +++ b/tests/testthat/test-getPermanova.R @@ -0,0 +1,249 @@ +# Tests for getPermanova +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +test_that("getPermanova returns a single test for all groups", { + set.seed(1) + res <- getPermanova(tse, counts ~ Geographical_location) + + expect_s3_class(res, "data.frame") + expect_identical(colnames(res), c("n", "Df", "R2", "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("getPermanova matches adonis2 for all groups", { + set.seed(1) + res <- getPermanova(tse, counts ~ Geographical_location) + + abundance <- t(SummarizedExperiment::assay(tse, "counts")) + set.seed(1) + expected <- vegan::adonis2( + vegan::vegdist(abundance, method = "bray") ~ group, + data = data.frame(group = tse$Geographical_location) + ) + + expect_equal(res$R2, expected$R2[[1L]]) + expect_equal(res$F, expected$F[[1L]]) + expect_equal(res$p, expected[["Pr(>F)"]][[1L]]) +}) + +test_that("getPermanova returns one row per pair of groups if pairwise", { + set.seed(1) + res <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) + + expect_s3_class(res, "data.frame") + expect_identical( + colnames(res), + c("group1", "group2", "n", "Df", "R2", "F", "p", "p.adj") + ) + expect_equal(nrow(res), 3L) + expect_equal( + res$n, + c( + sum(tse$Geographical_location %in% c("Ahmednagar", "Nashik")), + sum(tse$Geographical_location %in% c("Ahmednagar", "Pune")), + sum(tse$Geographical_location %in% c("Nashik", "Pune")) + ) + ) +}) + +test_that("getPermanova matches adonis2 for each pair of groups", { + set.seed(1) + res <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) + row <- res[res$group1 == "Ahmednagar" & res$group2 == "Pune", ] + + keep <- tse$Geographical_location %in% c("Ahmednagar", "Pune") + abundance <- t(SummarizedExperiment::assay(tse, "counts"))[keep, ] + set.seed(1) + expected <- vegan::adonis2( + vegan::vegdist(abundance, method = "bray") ~ group, + data = data.frame(group = factor( + tse$Geographical_location[keep], + levels = c("Ahmednagar", "Pune") + )) + ) + + expect_equal(row$R2, expected$R2[[1L]]) + expect_equal(row$F, expected$F[[1L]]) + expect_equal(row$Df, expected$Df[[1L]]) +}) + +test_that("getPermanova is reproducible with a seed", { + set.seed(1) + first <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) + set.seed(1) + second <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) + + expect_equal(first, second) +}) + +test_that("getPermanova adjusts p-values", { + set.seed(1) + res <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) + expect_equal(res$p.adj, stats::p.adjust(res$p, method = "BH")) + + set.seed(1) + res <- getPermanova( + tse, counts ~ Geographical_location, + pairwise = TRUE, p.adjust.method = "bonferroni" + ) + expect_equal(res$p.adj, stats::p.adjust(res$p, method = "bonferroni")) +}) + +test_that("getPermanova uses the method and permutations arguments", { + set.seed(1) + bray <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) + set.seed(1) + euclidean <- getPermanova( + tse, counts ~ Geographical_location, + pairwise = TRUE, method = "euclidean", permutations = 99L + ) + + expect_false(isTRUE(all.equal(bray$R2, euclidean$R2))) + # The smallest possible p-value is 1 / (permutations + 1) + expect_gte(min(euclidean$p), 1 / 100) +}) + +test_that("getPermanova ignores samples with missing group", { + tse$Geographical_location[1L] <- NA + set.seed(1) + res <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) + + expect_equal(sum(res$n[res$group1 == "Nashik" & res$group2 == "Pune"]), + sum(tse$Geographical_location %in% c("Nashik", "Pune")) + ) +}) + +test_that("getPermanova requires at least two groups", { + one_group <- tse[, tse$Geographical_location == "Pune"] + expect_error( + getPermanova(one_group, counts ~ Geographical_location), + "at least two groups" + ) +}) + +test_that("getPermanova fails with multiple RHS vars", { + expect_error( + getPermanova(tse, counts ~ Geographical_location + Gender), + "exactly one" + ) +}) + +test_that("getPermanova fails with unknown assay or variable", { + expect_error( + getPermanova(tse, nonexistent ~ Geographical_location), + "All formula variables must be in" + ) + expect_error( + getPermanova(tse, counts ~ nonexistent), + "All formula variables must be in" + ) +}) + +################################################################################ +# 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 +) + +test_that("getPermanova permutes within pairs with pair.by", { + set.seed(1) + res <- getPermanova( + paired_tse, counts ~ Geographical_location, + pairwise = TRUE, pair.by = "id" + ) + + abundance <- t(SummarizedExperiment::assay(paired_tse, "counts")) + 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") + )), + permutations = permute::how( + nperm = 999L, blocks = factor(paired_tse$id) + ) + ) + + expect_equal(nrow(res), 1L) + expect_equal(res$n, ncol(paired_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] + set.seed(1) + res <- getPermanova( + removed, counts ~ Geographical_location, + pairwise = TRUE, pair.by = "id" + ) + + # The sample without a partner is also left out + expect_equal(res$n, ncol(paired_tse) - 2L) +}) + +test_that("getPermanova pair.by gives different p-values than unpaired", { + set.seed(1) + unpaired <- getPermanova(paired_tse, counts ~ Geographical_location) + set.seed(1) + paired <- getPermanova( + paired_tse, counts ~ Geographical_location, pair.by = "id" + ) + + # The test statistic is the same, only the permutations differ + expect_equal(paired$F, unpaired$F) + expect_false(isTRUE(all.equal(paired$p, unpaired$p))) +}) + +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 + ) + set.seed(1) + res <- getPermanova( + three_groups, counts ~ Geographical_location, pair.by = "id" + ) + + # 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(nrow(res), 1L) +}) + +test_that("getPermanova returns NA if no pairs are shared", { + # No pairing ID is present in both groups + no_pairs <- paired_tse + no_pairs$id[no_pairs$Geographical_location == "Nashik"] <- + no_pairs$id[no_pairs$Geographical_location == "Nashik"] + 100L + set.seed(1) + res <- getPermanova( + no_pairs, counts ~ Geographical_location, + pairwise = TRUE, pair.by = "id" + ) + + expect_equal(res$n, 0L) + expect_true(is.na(res$p)) + expect_true(is.na(res$R2)) +}) + +test_that("getPermanova fails with unknown pair.by", { + expect_error( + getPermanova( + tse, counts ~ Geographical_location, pair.by = "nonexistent" + ), + "'pair.by' must be a column in colData" + ) +}) diff --git a/vignettes/daa.Rmd b/vignettes/daa.Rmd index b807ed8..8a95eb8 100644 --- a/vignettes/daa.Rmd +++ b/vignettes/daa.Rmd @@ -93,6 +93,27 @@ res <- getWilcoxonTest(tse, shannon ~ Geographical_location) head(res) ``` +## PERMANOVA + +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. + +```{r permanova} +set.seed(1) +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. + +```{r permanova-pairwise} +set.seed(1) +res <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) +res +``` + ## Wide-format methods For model-based approaches, use formula with the assay name on the LHS: From d286d9ec3af1586c7cf639ef126c6c3b81454014 Mon Sep 17 00:00:00 2001 From: TuomasBorman Date: Tue, 1 Dec 2026 09:03:54 +0000 Subject: [PATCH 2/2] Style code (GHA) --- R/getPermanova.R | 18 +++++++----------- R/getWilcoxonTest.R | 3 +-- R/utils.R | 10 +++++++--- tests/testthat/test-getPermanova.R | 12 ++++++++---- 4 files changed, 23 insertions(+), 20 deletions(-) diff --git a/R/getPermanova.R b/R/getPermanova.R index 27b7ce4..4cea31e 100644 --- a/R/getPermanova.R +++ b/R/getPermanova.R @@ -58,9 +58,8 @@ #' \code{\link[vegan:adonis2]{vegan::adonis2}} #' #' @export -getPermanova <- function( - tse, formula, pairwise = FALSE, method = "bray", permutations = 999L, - p.adjust.method = "BH", pair.by = NULL, ...) { +getPermanova <- function(tse, formula, pairwise = FALSE, method = "bray", permutations = 999L, + p.adjust.method = "BH", pair.by = NULL, ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE @@ -100,9 +99,8 @@ getPermanova <- function( #' #' @keywords internal #' @noRd -.calculate_pairwise_permanova <- function( - abundance, sample_data, group_column, method, permutations, - p.adjust.method, pair.by, ...) { +.calculate_pairwise_permanova <- function(abundance, sample_data, group_column, method, permutations, + p.adjust.method, pair.by, ...) { # All pairwise combinations of groups, e.g., A-B, A-C, B-C group_pairs <- .get_group_pairs(sample_data, group_column) results <- lapply(group_pairs, function(group_pair) { @@ -127,9 +125,8 @@ getPermanova <- function( #' @keywords internal #' @noRd #' @importFrom vegan adonis2 vegdist -.calculate_permanova <- function( - abundance, sample_data, groups, group_column, method, permutations, - pair.by, ...) { +.calculate_permanova <- function(abundance, sample_data, groups, group_column, method, permutations, + pair.by, ...) { # Samples that belong to the compared groups (and have a partner in all # groups if the samples are paired) in_groups <- .select_samples(sample_data, groups, group_column, pair.by) @@ -198,8 +195,7 @@ getPermanova <- function( #' @keywords internal #' @noRd #' @importFrom permute how -.get_permutation_scheme <- function( - pair.by, sample_data, in_groups, permutations) { +.get_permutation_scheme <- function(pair.by, sample_data, in_groups, permutations) { if (is.null(pair.by)) { return(how(nperm = permutations)) } diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index 047e6e5..44676d1 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -41,8 +41,7 @@ #' @importFrom rstatix wilcox_test #' @importFrom dplyr left_join #' @export -getWilcoxonTest <- function( - tse, formula, effect.size = c("cliff", "cohen"), pair.by = NULL, ...) { +getWilcoxonTest <- function(tse, formula, effect.size = c("cliff", "cohen"), pair.by = NULL, ...) { effect.size <- match.arg(effect.size) if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", diff --git a/R/utils.R b/R/utils.R index 8f7faa2..87e3ff5 100644 --- a/R/utils.R +++ b/R/utils.R @@ -136,9 +136,13 @@ .get_group_names <- function(df, group_column) { groups <- df[[group_column]] group_names <- if (is.factor(groups)) { - groups |> droplevels() |> levels() + groups |> + droplevels() |> + levels() } else { - groups |> unique() |> sort() + groups |> + unique() |> + sort() } if (length(group_names) < 2L) { stop("'", group_column, "' must have at least two groups.", @@ -281,7 +285,7 @@ #' @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() diff --git a/tests/testthat/test-getPermanova.R b/tests/testthat/test-getPermanova.R index 331cdc2..7d36dab 100644 --- a/tests/testthat/test-getPermanova.R +++ b/tests/testthat/test-getPermanova.R @@ -113,7 +113,8 @@ test_that("getPermanova ignores samples with missing group", { set.seed(1) res <- getPermanova(tse, counts ~ Geographical_location, pairwise = TRUE) - expect_equal(sum(res$n[res$group1 == "Nashik" & res$group2 == "Pune"]), + expect_equal( + sum(res$n[res$group1 == "Nashik" & res$group2 == "Pune"]), sum(tse$Geographical_location %in% c("Nashik", "Pune")) ) }) @@ -198,7 +199,8 @@ test_that("getPermanova pair.by gives different p-values than unpaired", { unpaired <- getPermanova(paired_tse, counts ~ Geographical_location) set.seed(1) paired <- getPermanova( - paired_tse, counts ~ Geographical_location, pair.by = "id" + paired_tse, counts ~ Geographical_location, + pair.by = "id" ) # The test statistic is the same, only the permutations differ @@ -215,7 +217,8 @@ test_that("getPermanova uses only IDs present in all groups with pair.by", { ) set.seed(1) res <- getPermanova( - three_groups, counts ~ Geographical_location, pair.by = "id" + three_groups, counts ~ Geographical_location, + pair.by = "id" ) # Nashik has the fewest samples (11), so 11 IDs in each of 3 groups @@ -242,7 +245,8 @@ test_that("getPermanova returns NA if no pairs are shared", { test_that("getPermanova fails with unknown pair.by", { expect_error( getPermanova( - tse, counts ~ Geographical_location, pair.by = "nonexistent" + tse, counts ~ Geographical_location, + pair.by = "nonexistent" ), "'pair.by' must be a column in colData" )