Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@ Imports:
effsize,
limma,
logistf,
permute,
rlang,
rms,
rstatix,
stats,
tidyr,
utils
utils,
vegan
Suggests:
mia,
BiocStyle,
Expand Down
6 changes: 6 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export(getKruskal)
export(getLimma)
export(getLm)
export(getOrm)
export(getPermanova)
export(getTTest)
export(getWilcoxonTest)
importFrom(SummarizedExperiment,
Expand Down Expand Up @@ -40,6 +41,7 @@ importFrom(logistf,
logistf,
logistf.control
)
importFrom(permute,how)
importFrom(rlang,
"!!",
.data,
Expand Down Expand Up @@ -69,3 +71,7 @@ importFrom(stats,
)
importFrom(tidyr,pivot_longer)
importFrom(utils,combn)
importFrom(vegan,
adonis2,
vegdist
)
22 changes: 0 additions & 22 deletions R/getEffectSize.R
Original file line number Diff line number Diff line change
Expand Up @@ -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}.
Expand Down
205 changes: 205 additions & 0 deletions R/getPermanova.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
#' @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))
}
6 changes: 3 additions & 3 deletions R/getWilcoxonTest.R
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -41,7 +41,7 @@
#' @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.",
Expand Down
50 changes: 47 additions & 3 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,46 @@
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
################################################################################
Expand Down Expand Up @@ -184,7 +224,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)

Expand All @@ -197,6 +237,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) {
Expand All @@ -208,7 +252,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)))) {
Expand Down Expand Up @@ -241,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()
Expand Down
Loading