From 5140e3d4f49433c75cce0516e357332bed3695cb Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Thu, 16 Apr 2026 22:40:10 +0300 Subject: [PATCH 1/9] Add Cliff's delta effect size to two-group Wilcoxon results --- DESCRIPTION | 1 + NAMESPACE | 1 + R/getWilcoxonTest.R | 27 ++++++++++++++++++++++++++- man/getWilcoxonTest.Rd | 4 +++- tests/testthat/test-getWilcoxonTest.R | 14 ++++++++++++++ 5 files changed, 45 insertions(+), 2 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index c62fef2..e565516 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -23,6 +23,7 @@ Depends: Imports: broom, dplyr, + effsize, limma, logistf, rlang, diff --git a/NAMESPACE b/NAMESPACE index f7a4613..9cf1a4f 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -21,6 +21,7 @@ importFrom(dplyr,left_join) importFrom(dplyr,mutate) importFrom(dplyr,n_distinct) importFrom(dplyr,ungroup) +importFrom(effsize,cliff.delta) importFrom(limma,eBayes) importFrom(limma,lmFit) importFrom(logistf,logistf) diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index 0d5a141..05a9452 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -12,7 +12,9 @@ #' samples in paired tests. (Default: \code{NULL}) #' @param ... Additional arguments passed to \code{wilcox_test}. #' -#' @return A \code{data.frame} with test results. +#' @return A \code{data.frame} with test results. For unpaired two-group +#' comparisons with non-empty results, the output also includes Cliff's delta +#' effect size columns. #' #' @examples #' data(peerj13075, package = "mia") @@ -20,6 +22,8 @@ #' tse <- mia::agglomerateByRank(tse, "phylum") #' res <- getWilcoxonTest(tse, counts ~ Geographical_location) #' +#' @importFrom dplyr bind_rows left_join n_distinct +#' @importFrom effsize cliff.delta #' @importFrom rstatix wilcox_test #' @export getWilcoxonTest <- function(tse, formula, pair.by = NULL, ...) { @@ -33,5 +37,26 @@ getWilcoxonTest <- function(tse, formula, pair.by = NULL, ...) { df = df, formula = formula, pair.by = pair.by, FUN = wilcox_test, ... ) + lhs <- .get_lhs(formula) + rhs <- .get_rhs(formula) + n_groups <- n_distinct(df[[rhs]], na.rm = TRUE) + + if (is.null(pair.by) && n_groups == 2L && nrow(res) > 0L) { + df_delta <- df[df$rownames %in% unique(res$rownames), , drop = FALSE] + delta_res <- lapply(split(df_delta, df_delta$rownames), function(.x) { + .x <- .x[stats::complete.cases(.x[, c(lhs, rhs), drop = FALSE]), , + drop = FALSE + ] + cd <- cliff.delta(formula = formula, data = .x) + data.frame( + cliff_delta = unname(cd$estimate), + cliff_delta_lower = cd$conf.int[1], + cliff_delta_upper = cd$conf.int[2], + cliff_delta_magnitude = unname(cd$magnitude) + ) + }) |> + bind_rows(.id = "rownames") + res <- left_join(res, delta_res, by = "rownames") + } return(res) } diff --git a/man/getWilcoxonTest.Rd b/man/getWilcoxonTest.Rd index 0dfb710..0ed349a 100644 --- a/man/getWilcoxonTest.Rd +++ b/man/getWilcoxonTest.Rd @@ -19,7 +19,9 @@ samples in paired tests. (Default: \code{NULL})} \item{...}{Additional arguments passed to \code{wilcox_test}.} } \value{ -A \code{data.frame} with test results. +A \code{data.frame} with test results. For unpaired two-group +comparisons with non-empty results, the output also includes Cliff's delta +effect size columns. } \description{ Performs Wilcoxon rank-sum test (Mann-Whitney U) to compare values between diff --git a/tests/testthat/test-getWilcoxonTest.R b/tests/testthat/test-getWilcoxonTest.R index fb74c18..7669235 100644 --- a/tests/testthat/test-getWilcoxonTest.R +++ b/tests/testthat/test-getWilcoxonTest.R @@ -8,9 +8,23 @@ test_that("getWilcoxonTest with assay works", { res <- getWilcoxonTest(tse, counts ~ Geographical_location) expect_s3_class(res, "data.frame") expect_true("p" %in% names(res)) + expect_false("cliff_delta" %in% names(res)) }) test_that("getWilcoxonTest with colData variable works", { res <- getWilcoxonTest(tse, shannon ~ Geographical_location) expect_s3_class(res, "data.frame") + expect_false("cliff_delta" %in% names(res)) +}) + +test_that("getWilcoxonTest adds Cliff's delta for unpaired two-group comparisons", { + tse_two <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] + res <- getWilcoxonTest(tse_two, counts ~ Geographical_location) + expect_s3_class(res, "data.frame") + expect_true(all(c( + "cliff_delta", + "cliff_delta_lower", + "cliff_delta_upper", + "cliff_delta_magnitude" + ) %in% names(res))) }) From 197e496ec0966afba9c195578f7c88e87dec72e4 Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Mon, 20 Apr 2026 12:52:47 +0300 Subject: [PATCH 2/9] up --- R/getWilcoxonTest.R | 44 ++++++++++----------- R/utils.R | 57 +++++++++++++++++++++++++++ man/getWilcoxonTest.Rd | 12 ++++-- tests/testthat/test-getWilcoxonTest.R | 21 +++++++++- 4 files changed, 105 insertions(+), 29 deletions(-) diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index 05a9452..9a75b4b 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -10,11 +10,14 @@ #' 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 to compute. +#' Supported values are \code{"none"} and \code{"cliff"}. +#' (Default: \code{"none"}) #' @param ... Additional arguments passed to \code{wilcox_test}. #' -#' @return A \code{data.frame} with test results. For unpaired two-group -#' comparisons with non-empty results, the output also includes Cliff's delta -#' effect size columns. +#' @return A \code{data.frame} with test results. If +#' \code{effect_size = "cliff"} and the comparison is unpaired with exactly +#' two groups, output also includes Cliff's delta effect size columns. #' #' @examples #' data(peerj13075, package = "mia") @@ -22,40 +25,33 @@ #' tse <- mia::agglomerateByRank(tse, "phylum") #' res <- getWilcoxonTest(tse, counts ~ Geographical_location) #' -#' @importFrom dplyr bind_rows left_join n_distinct -#' @importFrom effsize cliff.delta +#' @importFrom dplyr left_join #' @importFrom rstatix wilcox_test #' @export -getWilcoxonTest <- function(tse, formula, pair.by = NULL, ...) { +getWilcoxonTest <- function(tse, formula, pair.by = NULL, + effect_size = c("none", "cliff"), ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE ) } + effect_size <- match.arg(effect_size) + df <- .get_long_data(tse, formula, pair.by) res <- .calculate_rstatix( df = df, formula = formula, pair.by = pair.by, FUN = wilcox_test, ... ) - lhs <- .get_lhs(formula) - rhs <- .get_rhs(formula) - n_groups <- n_distinct(df[[rhs]], na.rm = TRUE) - if (is.null(pair.by) && n_groups == 2L && nrow(res) > 0L) { - df_delta <- df[df$rownames %in% unique(res$rownames), , drop = FALSE] - delta_res <- lapply(split(df_delta, df_delta$rownames), function(.x) { - .x <- .x[stats::complete.cases(.x[, c(lhs, rhs), drop = FALSE]), , - drop = FALSE - ] - cd <- cliff.delta(formula = formula, data = .x) - data.frame( - cliff_delta = unname(cd$estimate), - cliff_delta_lower = cd$conf.int[1], - cliff_delta_upper = cd$conf.int[2], - cliff_delta_magnitude = unname(cd$magnitude) - ) - }) |> - bind_rows(.id = "rownames") + delta_res <- .calculate_effect_size( + df = df, + formula = formula, + pair.by = pair.by, + effect_size = effect_size, + rownames_filter = res$rownames + ) + + if (!is.null(delta_res)) { res <- left_join(res, delta_res, by = "rownames") } return(res) diff --git a/R/utils.R b/R/utils.R index eb157d4..cfdab39 100644 --- a/R/utils.R +++ b/R/utils.R @@ -176,6 +176,63 @@ return(res) } +#' Calculate effect size per feature from long-format data +#' +#' Currently supports Cliff's delta for unpaired two-group comparisons. +#' +#' @keywords internal +#' @noRd +#' @importFrom dplyr bind_rows n_distinct +#' @importFrom effsize cliff.delta +.calculate_effect_size <- function(df, formula, pair.by = NULL, + effect_size = c("none", "cliff"), rownames_filter = NULL) { + effect_size <- match.arg(effect_size) + if (effect_size == "none") { + return(NULL) + } + + lhs <- .get_lhs(formula) + rhs <- .get_rhs(formula) + n_groups <- n_distinct(df[[rhs]], na.rm = TRUE) + + # Cliff's delta is defined here for unpaired two-group comparisons. + if (!is.null(pair.by) || n_groups != 2L) { + return(NULL) + } + + if (!is.null(rownames_filter)) { + df <- df[df$rownames %in% unique(rownames_filter), , drop = FALSE] + } + + if (nrow(df) == 0L) { + return(NULL) + } + + delta_res <- lapply(split(df, df$rownames), function(.x) { + .x <- .x[stats::complete.cases(.x[, c(lhs, rhs), drop = FALSE]), , + drop = FALSE + ] + if (nrow(.x) == 0L || n_distinct(.x[[rhs]], na.rm = TRUE) != 2L) { + return(NULL) + } + cd <- cliff.delta(formula = formula, data = .x) + data.frame( + cliff_delta = unname(cd$estimate), + cliff_delta_lower = cd$conf.int[1], + cliff_delta_upper = cd$conf.int[2], + cliff_delta_magnitude = unname(cd$magnitude) + ) + }) + + keep <- !vapply(delta_res, is.null, logical(1L)) + if (!any(keep)) { + return(NULL) + } + + delta_res <- bind_rows(delta_res[keep], .id = "rownames") + return(delta_res) +} + ################################################################################ # Wide-format data helper ################################################################################ diff --git a/man/getWilcoxonTest.Rd b/man/getWilcoxonTest.Rd index 0ed349a..bbef8fd 100644 --- a/man/getWilcoxonTest.Rd +++ b/man/getWilcoxonTest.Rd @@ -4,7 +4,7 @@ \alias{getWilcoxonTest} \title{Perform Wilcoxon rank-sum test} \usage{ -getWilcoxonTest(tse, formula, pair.by = NULL, ...) +getWilcoxonTest(tse, formula, pair.by = NULL, effect_size = c("none", "cliff"), ...) } \arguments{ \item{tse}{A \code{SummarizedExperiment} object.} @@ -16,12 +16,16 @@ 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 to compute. +Supported values are \code{"none"} and \code{"cliff"}. +(Default: \code{"none"})} + \item{...}{Additional arguments passed to \code{wilcox_test}.} } \value{ -A \code{data.frame} with test results. For unpaired two-group -comparisons with non-empty results, the output also includes Cliff's delta -effect size columns. +A \code{data.frame} with test results. If +\code{effect_size = "cliff"} and the comparison is unpaired with exactly +two groups, output also includes Cliff's delta effect size columns. } \description{ Performs Wilcoxon rank-sum test (Mann-Whitney U) to compare values between diff --git a/tests/testthat/test-getWilcoxonTest.R b/tests/testthat/test-getWilcoxonTest.R index 7669235..542c4a9 100644 --- a/tests/testthat/test-getWilcoxonTest.R +++ b/tests/testthat/test-getWilcoxonTest.R @@ -19,7 +19,11 @@ test_that("getWilcoxonTest with colData variable works", { test_that("getWilcoxonTest adds Cliff's delta for unpaired two-group comparisons", { tse_two <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] - res <- getWilcoxonTest(tse_two, counts ~ Geographical_location) + res <- getWilcoxonTest( + tse_two, + counts ~ Geographical_location, + effect_size = "cliff" + ) expect_s3_class(res, "data.frame") expect_true(all(c( "cliff_delta", @@ -28,3 +32,18 @@ test_that("getWilcoxonTest adds Cliff's delta for unpaired two-group comparisons "cliff_delta_magnitude" ) %in% names(res))) }) + +test_that("getWilcoxonTest does not add Cliff's delta for paired tests", { + tse_two <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] + tse_two$pair_id <- seq_len(ncol(tse_two)) + + res <- getWilcoxonTest( + tse_two, + counts ~ Geographical_location, + pair.by = "pair_id", + effect_size = "cliff" + ) + + expect_s3_class(res, "data.frame") + expect_false("cliff_delta" %in% names(res)) +}) From 0d42358f68af6a2aee200e3c1755bab251868d4b Mon Sep 17 00:00:00 2001 From: 0xMuluh <0xMuluh@users.noreply.github.com> Date: Mon, 20 Apr 2026 09:54:04 +0000 Subject: [PATCH 3/9] Style code (GHA) --- R/getWilcoxonTest.R | 2 +- R/utils.R | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index 9a75b4b..2eeecdd 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -29,7 +29,7 @@ #' @importFrom rstatix wilcox_test #' @export getWilcoxonTest <- function(tse, formula, pair.by = NULL, - effect_size = c("none", "cliff"), ...) { + effect_size = c("none", "cliff"), ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE diff --git a/R/utils.R b/R/utils.R index cfdab39..81e5d07 100644 --- a/R/utils.R +++ b/R/utils.R @@ -185,7 +185,7 @@ #' @importFrom dplyr bind_rows n_distinct #' @importFrom effsize cliff.delta .calculate_effect_size <- function(df, formula, pair.by = NULL, - effect_size = c("none", "cliff"), rownames_filter = NULL) { + effect_size = c("none", "cliff"), rownames_filter = NULL) { effect_size <- match.arg(effect_size) if (effect_size == "none") { return(NULL) @@ -298,7 +298,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() From a3769c72e10b87b4f567a12b6cf928c536ef46ca Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Thu, 30 Apr 2026 12:29:50 +0300 Subject: [PATCH 4/9] up --- NAMESPACE | 1 + R/getEffectSize.R | 29 +++++++++++ R/getWilcoxonTest.R | 39 ++++++++++----- R/utils.R | 72 +++++++++++++++++---------- man/getWilcoxonTest.Rd | 14 ++++-- tests/testthat/test-getWilcoxonTest.R | 30 ++++++++--- 6 files changed, 134 insertions(+), 51 deletions(-) create mode 100644 R/getEffectSize.R diff --git a/NAMESPACE b/NAMESPACE index 9cf1a4f..d3c30b4 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -22,6 +22,7 @@ importFrom(dplyr,mutate) importFrom(dplyr,n_distinct) importFrom(dplyr,ungroup) importFrom(effsize,cliff.delta) +importFrom(effsize,cohen.d) importFrom(limma,eBayes) importFrom(limma,lmFit) importFrom(logistf,logistf) diff --git a/R/getEffectSize.R b/R/getEffectSize.R new file mode 100644 index 0000000..fea254f --- /dev/null +++ b/R/getEffectSize.R @@ -0,0 +1,29 @@ +## Helper for effect size calculations + +#' Calculate effect sizes for features in a SummarizedExperiment +#' +#' Wrapper that computes per-feature effect sizes from long-format data. +#' +#' @param tse A SummarizedExperiment-like object. +#' @param formula A formula where LHS is feature/assay and RHS grouping. +#' @param method Character scalar, one of 'cliff' or 'cohen'. +#' @param pair.by Optional pairing column name (passed to .get_long_data). +#' @return A data.frame with a `rownames` column and method-specific columns. +#' @keywords internal +#' @noRd +getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), + pair.by = NULL) { + method <- match.arg(method) + df <- .get_long_data(tse, formula, pair.by) + + if (exists(".calculate_effect_size", mode = "function")) { + return(.calculate_effect_size( + df = df, + formula = formula, + pair.by = pair.by, + effect_size = method + )) + } + + return(NULL) +} diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index 2eeecdd..ef3f660 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -11,13 +11,13 @@ #' @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 to compute. -#' Supported values are \code{"none"} and \code{"cliff"}. +#' Supported values are \code{"none"}, \code{"cliff"}, and \code{"cohen"}. #' (Default: \code{"none"}) #' @param ... Additional arguments passed to \code{wilcox_test}. #' #' @return A \code{data.frame} with test results. If -#' \code{effect_size = "cliff"} and the comparison is unpaired with exactly -#' two groups, output also includes Cliff's delta effect size columns. +#' \code{effect_size = "cliff"} or \code{"cohen"} and the comparison is +#' unpaired with exactly two groups, output also includes effect size columns. #' #' @examples #' data(peerj13075, package = "mia") @@ -29,7 +29,7 @@ #' @importFrom rstatix wilcox_test #' @export getWilcoxonTest <- function(tse, formula, pair.by = NULL, - effect_size = c("none", "cliff"), ...) { + effect_size = c("none", "cliff", "cohen"), ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE @@ -43,16 +43,29 @@ getWilcoxonTest <- function(tse, formula, pair.by = NULL, pair.by = pair.by, FUN = wilcox_test, ... ) - delta_res <- .calculate_effect_size( - df = df, - formula = formula, - pair.by = pair.by, - effect_size = effect_size, - rownames_filter = res$rownames - ) + if (effect_size != "none") { + # Only compute effect sizes for unpaired two-group comparisons. + rhs <- .get_rhs(formula) + n_groups <- sum(!is.na(unique(df[[rhs]]))) + if (is.null(pair.by) && n_groups == 2L) { + # Pre-filter tse to only tested features to avoid computing effect sizes + # for features without test results. + if (length(res$rownames) > 0L) { + tse_sub <- tse[res$rownames, , drop = FALSE] + } else { + tse_sub <- tse[0, , drop = FALSE] + } - if (!is.null(delta_res)) { - res <- left_join(res, delta_res, by = "rownames") + delta_res <- getEffectSize( + tse = tse_sub, + formula = formula, + method = effect_size, + pair.by = pair.by + ) + if (!is.null(delta_res)) { + res <- left_join(res, delta_res, by = "rownames") + } + } } return(res) } diff --git a/R/utils.R b/R/utils.R index 81e5d07..001f8de 100644 --- a/R/utils.R +++ b/R/utils.R @@ -178,14 +178,14 @@ #' Calculate effect size per feature from long-format data #' -#' Currently supports Cliff's delta for unpaired two-group comparisons. +#' Currently supports generic effect-size output for unpaired two-group comparisons. #' #' @keywords internal #' @noRd #' @importFrom dplyr bind_rows n_distinct -#' @importFrom effsize cliff.delta +#' @importFrom effsize cliff.delta cohen.d .calculate_effect_size <- function(df, formula, pair.by = NULL, - effect_size = c("none", "cliff"), rownames_filter = NULL) { + effect_size = c("none", "cliff", "cohen")) { effect_size <- match.arg(effect_size) if (effect_size == "none") { return(NULL) @@ -193,22 +193,16 @@ lhs <- .get_lhs(formula) rhs <- .get_rhs(formula) - n_groups <- n_distinct(df[[rhs]], na.rm = TRUE) - - # Cliff's delta is defined here for unpaired two-group comparisons. - if (!is.null(pair.by) || n_groups != 2L) { - return(NULL) - } - - if (!is.null(rownames_filter)) { - df <- df[df$rownames %in% unique(rownames_filter), , drop = FALSE] - } if (nrow(df) == 0L) { return(NULL) } - delta_res <- lapply(split(df, df$rownames), function(.x) { + if (effect_size == "cliff") { + if (!is.null(pair.by)) { + return(NULL) + } + delta_res <- lapply(split(df, df$rownames), function(.x) { .x <- .x[stats::complete.cases(.x[, c(lhs, rhs), drop = FALSE]), , drop = FALSE ] @@ -216,21 +210,47 @@ return(NULL) } cd <- cliff.delta(formula = formula, data = .x) - data.frame( - cliff_delta = unname(cd$estimate), - cliff_delta_lower = cd$conf.int[1], - cliff_delta_upper = cd$conf.int[2], - cliff_delta_magnitude = unname(cd$magnitude) - ) + data.frame( + effect_size = unname(cd$estimate), + effect_size_lower = cd$conf.int[1], + effect_size_upper = cd$conf.int[2], + effect_size_magnitude = unname(cd$magnitude) + ) }) - - keep <- !vapply(delta_res, is.null, logical(1L)) - if (!any(keep)) { - return(NULL) + # remove NULLs and bind results + delta_res <- Filter(Negate(is.null), delta_res) + if (length(delta_res) == 0L) return(NULL) + delta_res <- bind_rows(delta_res, .id = "rownames") + return(delta_res) } - delta_res <- bind_rows(delta_res[keep], .id = "rownames") - return(delta_res) + if (effect_size == "cohen") { + if (!is.null(pair.by)) { + return(NULL) + } + res_list <- lapply(split(df, df$rownames), function(.x) { + .x <- .x[stats::complete.cases(.x[, c(lhs, rhs), drop = FALSE]), , + drop = FALSE + ] + if (nrow(.x) == 0L || n_distinct(.x[[rhs]], na.rm = TRUE) < 2L) { + return(NULL) + } + cd <- tryCatch(effsize::cohen.d(formula = formula, data = .x), + error = function(e) NULL + ) + if (is.null(cd)) return(NULL) + est <- if (!is.null(cd$estimate)) unname(cd$estimate) else NA_real_ + mag <- if (!is.null(cd$magnitude)) unname(cd$magnitude) else NA_character_ + data.frame( + effect_size = est, + effect_size_magnitude = mag, + stringsAsFactors = FALSE + ) + }) + res_list <- Filter(Negate(is.null), res_list) + if (length(res_list) == 0L) return(NULL) + return(bind_rows(res_list, .id = "rownames")) + } } ################################################################################ diff --git a/man/getWilcoxonTest.Rd b/man/getWilcoxonTest.Rd index bbef8fd..2807b8c 100644 --- a/man/getWilcoxonTest.Rd +++ b/man/getWilcoxonTest.Rd @@ -4,7 +4,13 @@ \alias{getWilcoxonTest} \title{Perform Wilcoxon rank-sum test} \usage{ -getWilcoxonTest(tse, formula, pair.by = NULL, effect_size = c("none", "cliff"), ...) +getWilcoxonTest( + tse, + formula, + pair.by = NULL, + effect_size = c("none", "cliff", "cohen"), + ... +) } \arguments{ \item{tse}{A \code{SummarizedExperiment} object.} @@ -17,15 +23,15 @@ grouping variable, e.g., \code{counts ~ Group}.} samples in paired tests. (Default: \code{NULL})} \item{effect_size}{\code{Character scalar}. Effect size to compute. -Supported values are \code{"none"} and \code{"cliff"}. +Supported values are \code{"none"}, \code{"cliff"}, and \code{"cohen"}. (Default: \code{"none"})} \item{...}{Additional arguments passed to \code{wilcox_test}.} } \value{ A \code{data.frame} with test results. If -\code{effect_size = "cliff"} and the comparison is unpaired with exactly -two groups, output also includes Cliff's delta effect size columns. +\code{effect_size = "cliff"} or \code{"cohen"} and the comparison is +unpaired with exactly two groups, output also includes effect size columns. } \description{ Performs Wilcoxon rank-sum test (Mann-Whitney U) to compare values between diff --git a/tests/testthat/test-getWilcoxonTest.R b/tests/testthat/test-getWilcoxonTest.R index 542c4a9..a2963da 100644 --- a/tests/testthat/test-getWilcoxonTest.R +++ b/tests/testthat/test-getWilcoxonTest.R @@ -8,16 +8,16 @@ test_that("getWilcoxonTest with assay works", { res <- getWilcoxonTest(tse, counts ~ Geographical_location) expect_s3_class(res, "data.frame") expect_true("p" %in% names(res)) - expect_false("cliff_delta" %in% names(res)) + expect_false("effect_size" %in% names(res)) }) test_that("getWilcoxonTest with colData variable works", { res <- getWilcoxonTest(tse, shannon ~ Geographical_location) expect_s3_class(res, "data.frame") - expect_false("cliff_delta" %in% names(res)) + expect_false("effect_size" %in% names(res)) }) -test_that("getWilcoxonTest adds Cliff's delta for unpaired two-group comparisons", { +test_that("getWilcoxonTest adds effect size for unpaired two-group comparisons", { tse_two <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] res <- getWilcoxonTest( tse_two, @@ -26,10 +26,24 @@ test_that("getWilcoxonTest adds Cliff's delta for unpaired two-group comparisons ) expect_s3_class(res, "data.frame") expect_true(all(c( - "cliff_delta", - "cliff_delta_lower", - "cliff_delta_upper", - "cliff_delta_magnitude" + "effect_size", + "effect_size_lower", + "effect_size_upper", + "effect_size_magnitude" + ) %in% names(res))) +}) + +test_that("getWilcoxonTest adds Cohen's d for unpaired two-group comparisons", { + tse_two <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] + res <- getWilcoxonTest( + tse_two, + counts ~ Geographical_location, + effect_size = "cohen" + ) + expect_s3_class(res, "data.frame") + expect_true(all(c( + "effect_size", + "effect_size_magnitude" ) %in% names(res))) }) @@ -45,5 +59,5 @@ test_that("getWilcoxonTest does not add Cliff's delta for paired tests", { ) expect_s3_class(res, "data.frame") - expect_false("cliff_delta" %in% names(res)) + expect_false("effect_size" %in% names(res)) }) From 731703975c7b115e480b36a777e1ce98179ef795 Mon Sep 17 00:00:00 2001 From: 0xMuluh <0xMuluh@users.noreply.github.com> Date: Thu, 30 Apr 2026 09:36:35 +0000 Subject: [PATCH 5/9] Style code (GHA) --- R/getWilcoxonTest.R | 6 ++++-- R/utils.R | 30 ++++++++++++++++++------------ 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index ef3f660..cd80f4a 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -28,8 +28,10 @@ #' @importFrom dplyr left_join #' @importFrom rstatix wilcox_test #' @export -getWilcoxonTest <- function(tse, formula, pair.by = NULL, - effect_size = c("none", "cliff", "cohen"), ...) { +getWilcoxonTest <- function( + tse, formula, pair.by = NULL, + effect_size = c("none", "cliff", "cohen"), ... +) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE diff --git a/R/utils.R b/R/utils.R index 001f8de..23767a9 100644 --- a/R/utils.R +++ b/R/utils.R @@ -185,7 +185,7 @@ #' @importFrom dplyr bind_rows n_distinct #' @importFrom effsize cliff.delta cohen.d .calculate_effect_size <- function(df, formula, pair.by = NULL, - effect_size = c("none", "cliff", "cohen")) { + effect_size = c("none", "cliff", "cohen")) { effect_size <- match.arg(effect_size) if (effect_size == "none") { return(NULL) @@ -203,23 +203,25 @@ return(NULL) } delta_res <- lapply(split(df, df$rownames), function(.x) { - .x <- .x[stats::complete.cases(.x[, c(lhs, rhs), drop = FALSE]), , - drop = FALSE - ] - if (nrow(.x) == 0L || n_distinct(.x[[rhs]], na.rm = TRUE) != 2L) { - return(NULL) - } - cd <- cliff.delta(formula = formula, data = .x) + .x <- .x[stats::complete.cases(.x[, c(lhs, rhs), drop = FALSE]), , + drop = FALSE + ] + if (nrow(.x) == 0L || n_distinct(.x[[rhs]], na.rm = TRUE) != 2L) { + return(NULL) + } + cd <- cliff.delta(formula = formula, data = .x) data.frame( effect_size = unname(cd$estimate), effect_size_lower = cd$conf.int[1], effect_size_upper = cd$conf.int[2], effect_size_magnitude = unname(cd$magnitude) ) - }) + }) # remove NULLs and bind results delta_res <- Filter(Negate(is.null), delta_res) - if (length(delta_res) == 0L) return(NULL) + if (length(delta_res) == 0L) { + return(NULL) + } delta_res <- bind_rows(delta_res, .id = "rownames") return(delta_res) } @@ -238,7 +240,9 @@ cd <- tryCatch(effsize::cohen.d(formula = formula, data = .x), error = function(e) NULL ) - if (is.null(cd)) return(NULL) + if (is.null(cd)) { + return(NULL) + } est <- if (!is.null(cd$estimate)) unname(cd$estimate) else NA_real_ mag <- if (!is.null(cd$magnitude)) unname(cd$magnitude) else NA_character_ data.frame( @@ -248,7 +252,9 @@ ) }) res_list <- Filter(Negate(is.null), res_list) - if (length(res_list) == 0L) return(NULL) + if (length(res_list) == 0L) { + return(NULL) + } return(bind_rows(res_list, .id = "rownames")) } } From 1cea5c61cbe63262a9236bcf26ec014182507d18 Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Tue, 13 Oct 2026 00:53:14 +0300 Subject: [PATCH 6/9] Add getEffectSize and effect.size option to getWilcoxonTest getEffectSize() calculates Cliff's delta or Cohen's d with effsize for each feature and pair of groups. getWilcoxonTest(effect.size = ) adds it to the test results. Replaces the earlier internal implementation, as suggested in review. --- DESCRIPTION | 3 +- NAMESPACE | 2 + R/getEffectSize.R | 119 +++++++++++++++++++++----- R/getWilcoxonTest.R | 64 +++++++------- R/utils.R | 85 +----------------- man/getEffectSize.Rd | 51 +++++++++++ man/getWilcoxonTest.Rd | 23 +++-- tests/testthat/test-getEffectSize.R | 51 +++++++++++ tests/testthat/test-getWilcoxonTest.R | 55 ++++-------- 9 files changed, 258 insertions(+), 195 deletions(-) create mode 100644 man/getEffectSize.Rd create mode 100644 tests/testthat/test-getEffectSize.R diff --git a/DESCRIPTION b/DESCRIPTION index e565516..d55f883 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -30,7 +30,8 @@ Imports: rms, rstatix, stats, - tidyr + tidyr, + utils Suggests: mia, BiocStyle, diff --git a/NAMESPACE b/NAMESPACE index d3c30b4..3351380 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,6 +1,7 @@ # Generated by roxygen2: do not edit by hand export(getAnova) +export(getEffectSize) export(getFirth) export(getKruskal) export(getLimma) @@ -44,3 +45,4 @@ importFrom(stats,pchisq) importFrom(stats,terms) importFrom(stats,var) importFrom(tidyr,pivot_longer) +importFrom(utils,combn) diff --git a/R/getEffectSize.R b/R/getEffectSize.R index fea254f..1597bce 100644 --- a/R/getEffectSize.R +++ b/R/getEffectSize.R @@ -1,29 +1,102 @@ -## Helper for effect size calculations - -#' Calculate effect sizes for features in a SummarizedExperiment +#' @title Calculate effect sizes between groups #' -#' Wrapper that computes per-feature effect sizes from long-format data. +#' @description +#' Calculates effect sizes between each pair of groups with Cliff's delta or +#' Cohen's d. #' -#' @param tse A SummarizedExperiment-like object. -#' @param formula A formula where LHS is feature/assay and RHS grouping. -#' @param method Character scalar, one of 'cliff' or 'cohen'. -#' @param pair.by Optional pairing column name (passed to .get_long_data). -#' @return A data.frame with a `rownames` column and method-specific columns. -#' @keywords internal -#' @noRd -getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), - pair.by = NULL) { +#' @details +#' 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. +#' +#' Groups are compared pairwise in the same order as in +#' \code{\link{getWilcoxonTest}}. Positive values mean that values are higher +#' in \code{group1} than in \code{group2}. +#' +#' @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 method \code{Character scalar}. Effect size to calculate, +#' \code{"cliff"} or \code{"cohen"}. (Default: \code{"cliff"}) +#' @param ... Additional arguments passed to \code{effsize::cliff.delta} or +#' \code{effsize::cohen.d}. +#' +#' @return A \code{data.frame} with one row per feature and pair of groups, +#' and columns \code{rownames}, \code{group1}, \code{group2}, +#' \code{effsize}, \code{conf.low}, \code{conf.high} and \code{magnitude}. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' res <- getEffectSize(tse, counts ~ Geographical_location) +#' +#' @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"), ...) { + if (length(all.vars(formula[[3]])) != 1L) { + stop("Formula RHS must specify exactly one grouping variable.", + call. = FALSE + ) + } method <- match.arg(method) - df <- .get_long_data(tse, formula, pair.by) + df <- .get_long_data(tse, formula) + res <- .calculate_effect_size(df, formula, method, ...) + return(res) +} - if (exists(".calculate_effect_size", mode = "function")) { - return(.calculate_effect_size( - df = df, - formula = formula, - pair.by = pair.by, - effect_size = method - )) +#' Calculate effect size for each feature and pair of groups +#' +#' @keywords internal +#' @noRd +#' @importFrom effsize cliff.delta cohen.d +#' @importFrom utils combn +.calculate_effect_size <- function(df, formula, method, ...) { + lhs <- .get_lhs(formula) + rhs <- .get_rhs(formula) + FUN <- switch(method, cliff = cliff.delta, cohen = cohen.d) + # Pair groups in the same order as rstatix does + group <- df[[rhs]] + groups <- if (is.factor(group)) levels(droplevels(group)) else + sort(unique(group)) + if (length(groups) < 2L) { + stop("'", rhs, "' must have at least two groups.", call. = FALSE) } - - return(NULL) + pairs <- combn(as.character(groups), 2L, simplify = FALSE) + # Calculate effect size for each feature and pair of groups + res <- lapply(split(df, df[["rownames"]]), function(feat) { + feat_res <- lapply(pairs, function(pair) { + keep <- feat[[rhs]] %in% pair & !is.na(feat[[lhs]]) + values <- feat[[lhs]][keep] + groups <- factor(feat[[rhs]][keep], levels = pair) + res <- data.frame( + rownames = feat[["rownames"]][[1L]], + group1 = pair[[1L]], + group2 = pair[[2L]], + effsize = NA_real_, + conf.low = NA_real_, + conf.high = NA_real_, + magnitude = NA_character_ + ) + # Effect size cannot be calculated if a group has no values + if (any(table(groups) == 0L)) { + return(res) + } + es <- FUN(values, groups, ...) + res[["effsize"]] <- unname(es[["estimate"]]) + res[["conf.low"]] <- es[["conf.int"]][[1L]] + res[["conf.high"]] <- es[["conf.int"]][[2L]] + res[["magnitude"]] <- as.character(es[["magnitude"]]) + return(res) + }) + do.call(rbind, feat_res) + }) + res <- do.call(rbind, res) + rownames(res) <- NULL + return(res) } diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index cd80f4a..2d990cb 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -10,14 +10,13 @@ #' 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 to compute. -#' Supported values are \code{"none"}, \code{"cliff"}, and \code{"cohen"}. -#' (Default: \code{"none"}) +#' @param effect.size \code{NULL} or \code{Character scalar}. If +#' \code{"cliff"} or \code{"cohen"}, the effect size from +#' \code{\link{getEffectSize}} is added to the results. Not supported for +#' paired tests. (Default: \code{NULL}) #' @param ... Additional arguments passed to \code{wilcox_test}. #' -#' @return A \code{data.frame} with test results. If -#' \code{effect_size = "cliff"} or \code{"cohen"} and the comparison is -#' unpaired with exactly two groups, output also includes effect size columns. +#' @return A \code{data.frame} with test results. #' #' @examples #' data(peerj13075, package = "mia") @@ -25,49 +24,44 @@ #' tse <- mia::agglomerateByRank(tse, "phylum") #' res <- getWilcoxonTest(tse, counts ~ Geographical_location) #' -#' @importFrom dplyr left_join +#' # Add Cliff's delta +#' res <- getWilcoxonTest( +#' tse, counts ~ Geographical_location, effect.size = "cliff") +#' #' @importFrom rstatix wilcox_test +#' @importFrom dplyr left_join #' @export getWilcoxonTest <- function( - tse, formula, pair.by = NULL, - effect_size = c("none", "cliff", "cohen"), ... -) { + tse, formula, pair.by = NULL, effect.size = NULL, ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE ) } - effect_size <- match.arg(effect_size) - + if (!is.null(effect.size)) { + if (!is.null(pair.by)) { + stop("'effect.size' is not supported for paired tests.", + call. = FALSE + ) + } + effect.size <- match.arg(effect.size, c("cliff", "cohen")) + } df <- .get_long_data(tse, formula, pair.by) res <- .calculate_rstatix( df = df, formula = formula, pair.by = pair.by, FUN = wilcox_test, ... ) - - if (effect_size != "none") { - # Only compute effect sizes for unpaired two-group comparisons. + if (!is.null(effect.size)) { + # Only groups that were tested for each feature rhs <- .get_rhs(formula) - n_groups <- sum(!is.na(unique(df[[rhs]]))) - if (is.null(pair.by) && n_groups == 2L) { - # Pre-filter tse to only tested features to avoid computing effect sizes - # for features without test results. - if (length(res$rownames) > 0L) { - tse_sub <- tse[res$rownames, , drop = FALSE] - } else { - tse_sub <- tse[0, , drop = FALSE] - } - - delta_res <- getEffectSize( - tse = tse_sub, - formula = formula, - method = effect_size, - pair.by = pair.by - ) - if (!is.null(delta_res)) { - res <- left_join(res, delta_res, by = "rownames") - } - } + tested <- c( + paste(res[["rownames"]], res[["group1"]]), + paste(res[["rownames"]], res[["group2"]]) + ) + df <- df[paste(df[["rownames"]], df[[rhs]]) %in% tested, , + drop = FALSE] + es <- .calculate_effect_size(df, formula, effect.size) + res <- left_join(res, es, by = c("rownames", "group1", "group2")) } return(res) } diff --git a/R/utils.R b/R/utils.R index 23767a9..eb157d4 100644 --- a/R/utils.R +++ b/R/utils.R @@ -176,89 +176,6 @@ return(res) } -#' Calculate effect size per feature from long-format data -#' -#' Currently supports generic effect-size output for unpaired two-group comparisons. -#' -#' @keywords internal -#' @noRd -#' @importFrom dplyr bind_rows n_distinct -#' @importFrom effsize cliff.delta cohen.d -.calculate_effect_size <- function(df, formula, pair.by = NULL, - effect_size = c("none", "cliff", "cohen")) { - effect_size <- match.arg(effect_size) - if (effect_size == "none") { - return(NULL) - } - - lhs <- .get_lhs(formula) - rhs <- .get_rhs(formula) - - if (nrow(df) == 0L) { - return(NULL) - } - - if (effect_size == "cliff") { - if (!is.null(pair.by)) { - return(NULL) - } - delta_res <- lapply(split(df, df$rownames), function(.x) { - .x <- .x[stats::complete.cases(.x[, c(lhs, rhs), drop = FALSE]), , - drop = FALSE - ] - if (nrow(.x) == 0L || n_distinct(.x[[rhs]], na.rm = TRUE) != 2L) { - return(NULL) - } - cd <- cliff.delta(formula = formula, data = .x) - data.frame( - effect_size = unname(cd$estimate), - effect_size_lower = cd$conf.int[1], - effect_size_upper = cd$conf.int[2], - effect_size_magnitude = unname(cd$magnitude) - ) - }) - # remove NULLs and bind results - delta_res <- Filter(Negate(is.null), delta_res) - if (length(delta_res) == 0L) { - return(NULL) - } - delta_res <- bind_rows(delta_res, .id = "rownames") - return(delta_res) - } - - if (effect_size == "cohen") { - if (!is.null(pair.by)) { - return(NULL) - } - res_list <- lapply(split(df, df$rownames), function(.x) { - .x <- .x[stats::complete.cases(.x[, c(lhs, rhs), drop = FALSE]), , - drop = FALSE - ] - if (nrow(.x) == 0L || n_distinct(.x[[rhs]], na.rm = TRUE) < 2L) { - return(NULL) - } - cd <- tryCatch(effsize::cohen.d(formula = formula, data = .x), - error = function(e) NULL - ) - if (is.null(cd)) { - return(NULL) - } - est <- if (!is.null(cd$estimate)) unname(cd$estimate) else NA_real_ - mag <- if (!is.null(cd$magnitude)) unname(cd$magnitude) else NA_character_ - data.frame( - effect_size = est, - effect_size_magnitude = mag, - stringsAsFactors = FALSE - ) - }) - res_list <- Filter(Negate(is.null), res_list) - if (length(res_list) == 0L) { - return(NULL) - } - return(bind_rows(res_list, .id = "rownames")) - } -} - ################################################################################ # Wide-format data helper ################################################################################ @@ -324,7 +241,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/man/getEffectSize.Rd b/man/getEffectSize.Rd new file mode 100644 index 0000000..a4a33f7 --- /dev/null +++ b/man/getEffectSize.Rd @@ -0,0 +1,51 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getEffectSize.R +\name{getEffectSize} +\alias{getEffectSize} +\title{Calculate effect sizes between groups} +\usage{ +getEffectSize(tse, formula, method = c("cliff", "cohen"), ...) +} +\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{method}{\code{Character scalar}. Effect size to calculate, +\code{"cliff"} or \code{"cohen"}. (Default: \code{"cliff"})} + +\item{...}{Additional arguments passed to \code{effsize::cliff.delta} or +\code{effsize::cohen.d}.} +} +\value{ +A \code{data.frame} with one row per feature and pair of groups, +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. +} +\details{ +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. + +Groups are compared pairwise in the same order as in +\code{\link{getWilcoxonTest}}. Positive values mean that values are higher +in \code{group1} than in \code{group2}. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +res <- getEffectSize(tse, counts ~ Geographical_location) + +} +\seealso{ +\code{\link[effsize:cliff.delta]{effsize::cliff.delta}}, +\code{\link[effsize:cohen.d]{effsize::cohen.d}} +} diff --git a/man/getWilcoxonTest.Rd b/man/getWilcoxonTest.Rd index 2807b8c..56ddfc2 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, - pair.by = NULL, - effect_size = c("none", "cliff", "cohen"), - ... -) +getWilcoxonTest(tse, formula, pair.by = NULL, effect.size = NULL, ...) } \arguments{ \item{tse}{A \code{SummarizedExperiment} object.} @@ -22,16 +16,15 @@ 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 to compute. -Supported values are \code{"none"}, \code{"cliff"}, and \code{"cohen"}. -(Default: \code{"none"})} +\item{effect.size}{\code{NULL} or \code{Character scalar}. If +\code{"cliff"} or \code{"cohen"}, the effect size from +\code{\link{getEffectSize}} is added to the results. Not supported for +paired tests. (Default: \code{NULL})} \item{...}{Additional arguments passed to \code{wilcox_test}.} } \value{ -A \code{data.frame} with test results. If -\code{effect_size = "cliff"} or \code{"cohen"} and the comparison is -unpaired with exactly two groups, output also includes effect size columns. +A \code{data.frame} with test results. } \description{ Performs Wilcoxon rank-sum test (Mann-Whitney U) to compare values between @@ -43,4 +36,8 @@ tse <- peerj13075 tse <- mia::agglomerateByRank(tse, "phylum") res <- getWilcoxonTest(tse, counts ~ Geographical_location) +# Add Cliff's delta +res <- getWilcoxonTest( + tse, counts ~ Geographical_location, effect.size = "cliff") + } diff --git a/tests/testthat/test-getEffectSize.R b/tests/testthat/test-getEffectSize.R new file mode 100644 index 0000000..8d9204f --- /dev/null +++ b/tests/testthat/test-getEffectSize.R @@ -0,0 +1,51 @@ +# Tests for getEffectSize +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") + +test_that("getEffectSize matches effsize for each feature and pair", { + res <- getEffectSize(tse, counts ~ Geographical_location) + row <- res[res$rownames == "Firmicutes" & + res$group1 == "Ahmednagar" & res$group2 == "Pune", ] + + keep <- tse$Geographical_location %in% c("Ahmednagar", "Pune") + expected <- effsize::cliff.delta( + SummarizedExperiment::assay(tse, "counts")["Firmicutes", keep], + factor(tse$Geographical_location[keep], + levels = c("Ahmednagar", "Pune")) + ) + + expect_equal(row$effsize, unname(expected$estimate)) + expect_equal(c(row$conf.low, row$conf.high), unname(expected$conf.int)) + expect_equal(row$magnitude, as.character(expected$magnitude)) +}) + +test_that("getEffectSize calculates Cohen's d", { + res <- getEffectSize(tse, counts ~ Gender, method = "cohen") + row <- res[res$rownames == "Firmicutes", ] + + expected <- effsize::cohen.d( + SummarizedExperiment::assay(tse, "counts")["Firmicutes", ], + factor(tse$Gender, levels = c(row$group1, row$group2)) + ) + + expect_equal(row$effsize, unname(expected$estimate)) +}) + +test_that("getEffectSize returns every feature and pair of groups", { + res <- getEffectSize(tse, counts ~ Geographical_location) + + expect_identical( + colnames(res), + c("rownames", "group1", "group2", "effsize", "conf.low", + "conf.high", "magnitude") + ) + expect_equal(nrow(res), nrow(tse) * 3L) +}) + +test_that("getEffectSize requires one grouping variable", { + expect_error( + getEffectSize(tse, counts ~ Gender + Diet), + "exactly one grouping variable" + ) +}) diff --git a/tests/testthat/test-getWilcoxonTest.R b/tests/testthat/test-getWilcoxonTest.R index a2963da..bd33d7b 100644 --- a/tests/testthat/test-getWilcoxonTest.R +++ b/tests/testthat/test-getWilcoxonTest.R @@ -8,56 +8,33 @@ test_that("getWilcoxonTest with assay works", { res <- getWilcoxonTest(tse, counts ~ Geographical_location) expect_s3_class(res, "data.frame") expect_true("p" %in% names(res)) - expect_false("effect_size" %in% names(res)) }) test_that("getWilcoxonTest with colData variable works", { res <- getWilcoxonTest(tse, shannon ~ Geographical_location) expect_s3_class(res, "data.frame") - expect_false("effect_size" %in% names(res)) }) -test_that("getWilcoxonTest adds effect size for unpaired two-group comparisons", { - tse_two <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] +test_that("getWilcoxonTest adds effect sizes for each comparison", { res <- getWilcoxonTest( - tse_two, - counts ~ Geographical_location, - effect_size = "cliff" + tse, counts ~ Geographical_location, effect.size = "cliff" ) - expect_s3_class(res, "data.frame") - expect_true(all(c( - "effect_size", - "effect_size_lower", - "effect_size_upper", - "effect_size_magnitude" - ) %in% names(res))) -}) - -test_that("getWilcoxonTest adds Cohen's d for unpaired two-group comparisons", { - tse_two <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] - res <- getWilcoxonTest( - tse_two, - counts ~ Geographical_location, - effect_size = "cohen" + 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_s3_class(res, "data.frame") - expect_true(all(c( - "effect_size", - "effect_size_magnitude" - ) %in% names(res))) -}) -test_that("getWilcoxonTest does not add Cliff's delta for paired tests", { - tse_two <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] - tse_two$pair_id <- seq_len(ncol(tse_two)) + expect_equal(nrow(merged), nrow(res)) + expect_equal(merged$effsize.x, merged$effsize.y) +}) - res <- getWilcoxonTest( - tse_two, - counts ~ Geographical_location, - pair.by = "pair_id", - effect_size = "cliff" +test_that("getWilcoxonTest rejects effect sizes for paired tests", { + expect_error( + getWilcoxonTest( + tse, counts ~ Gender, pair.by = "Diet", effect.size = "cliff" + ), + "not supported for paired tests" ) - - expect_s3_class(res, "data.frame") - expect_false("effect_size" %in% names(res)) }) From 0eceb3a79e6db68112f70b22a0e6907d272c1970 Mon Sep 17 00:00:00 2001 From: 0xMuluh <0xMuluh@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:55:18 +0000 Subject: [PATCH 7/9] Style code (GHA) --- R/getEffectSize.R | 10 ++++++++-- R/getWilcoxonTest.R | 10 ++++++---- tests/testthat/test-getEffectSize.R | 9 ++++++--- tests/testthat/test-getWilcoxonTest.R | 6 ++++-- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/R/getEffectSize.R b/R/getEffectSize.R index 1597bce..bbff905 100644 --- a/R/getEffectSize.R +++ b/R/getEffectSize.R @@ -59,11 +59,17 @@ getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), ...) { .calculate_effect_size <- function(df, formula, method, ...) { lhs <- .get_lhs(formula) rhs <- .get_rhs(formula) - FUN <- switch(method, cliff = cliff.delta, cohen = cohen.d) + FUN <- switch(method, + cliff = cliff.delta, + cohen = cohen.d + ) # Pair groups in the same order as rstatix does group <- df[[rhs]] - groups <- if (is.factor(group)) levels(droplevels(group)) else + groups <- if (is.factor(group)) { + levels(droplevels(group)) + } else { sort(unique(group)) + } if (length(groups) < 2L) { stop("'", rhs, "' must have at least two groups.", call. = FALSE) } diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index 2d990cb..7612b5d 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -26,13 +26,14 @@ #' #' # Add Cliff's delta #' res <- getWilcoxonTest( -#' tse, counts ~ Geographical_location, effect.size = "cliff") +#' tse, counts ~ Geographical_location, +#' effect.size = "cliff" +#' ) #' #' @importFrom rstatix wilcox_test #' @importFrom dplyr left_join #' @export -getWilcoxonTest <- function( - tse, formula, pair.by = NULL, effect.size = NULL, ...) { +getWilcoxonTest <- function(tse, formula, pair.by = NULL, effect.size = NULL, ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE @@ -59,7 +60,8 @@ getWilcoxonTest <- function( paste(res[["rownames"]], res[["group2"]]) ) df <- df[paste(df[["rownames"]], df[[rhs]]) %in% tested, , - drop = FALSE] + drop = FALSE + ] es <- .calculate_effect_size(df, formula, effect.size) res <- left_join(res, es, by = c("rownames", "group1", "group2")) } diff --git a/tests/testthat/test-getEffectSize.R b/tests/testthat/test-getEffectSize.R index 8d9204f..684dee1 100644 --- a/tests/testthat/test-getEffectSize.R +++ b/tests/testthat/test-getEffectSize.R @@ -12,7 +12,8 @@ test_that("getEffectSize matches effsize for each feature and pair", { expected <- effsize::cliff.delta( SummarizedExperiment::assay(tse, "counts")["Firmicutes", keep], factor(tse$Geographical_location[keep], - levels = c("Ahmednagar", "Pune")) + levels = c("Ahmednagar", "Pune") + ) ) expect_equal(row$effsize, unname(expected$estimate)) @@ -37,8 +38,10 @@ test_that("getEffectSize returns every feature and pair of groups", { expect_identical( colnames(res), - c("rownames", "group1", "group2", "effsize", "conf.low", - "conf.high", "magnitude") + c( + "rownames", "group1", "group2", "effsize", "conf.low", + "conf.high", "magnitude" + ) ) expect_equal(nrow(res), nrow(tse) * 3L) }) diff --git a/tests/testthat/test-getWilcoxonTest.R b/tests/testthat/test-getWilcoxonTest.R index bd33d7b..bfded5c 100644 --- a/tests/testthat/test-getWilcoxonTest.R +++ b/tests/testthat/test-getWilcoxonTest.R @@ -17,7 +17,8 @@ test_that("getWilcoxonTest with colData variable works", { test_that("getWilcoxonTest adds effect sizes for each comparison", { res <- getWilcoxonTest( - tse, counts ~ Geographical_location, effect.size = "cliff" + tse, counts ~ Geographical_location, + effect.size = "cliff" ) es <- getEffectSize(tse, counts ~ Geographical_location) merged <- merge( @@ -33,7 +34,8 @@ test_that("getWilcoxonTest adds effect sizes for each comparison", { test_that("getWilcoxonTest rejects effect sizes for paired tests", { expect_error( getWilcoxonTest( - tse, counts ~ Gender, pair.by = "Diet", effect.size = "cliff" + tse, counts ~ Gender, + pair.by = "Diet", effect.size = "cliff" ), "not supported for paired tests" ) From c3a19ee6d76929a241bb793812b0bc7cb3df673d Mon Sep 17 00:00:00 2001 From: Tuomas Borman Date: Tue, 1 Dec 2026 08:48:26 +0200 Subject: [PATCH 8/9] up --- DESCRIPTION | 2 +- NAMESPACE | 83 ++++++----- R/getEffectSize.R | 190 +++++++++++++++++++------- R/getWilcoxonTest.R | 54 ++++---- man/getEffectSize.Rd | 9 +- man/getWilcoxonTest.Rd | 37 +++-- tests/testthat/test-getEffectSize.R | 127 +++++++++++++++++ tests/testthat/test-getWilcoxonTest.R | 80 +++++++++-- 8 files changed, 451 insertions(+), 131 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index d55f883..7d41e26 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -15,7 +15,6 @@ BugReports: https://github.com/microbiome/daa/issues/ biocViews: Software, Microbiome Encoding: UTF-8 Roxygen: list(markdown = TRUE) -RoxygenNote: 7.3.3 Depends: R (>= 4.5.0), SingleCellExperiment, @@ -40,3 +39,4 @@ Suggests: testthat Config/testthat/edition: 3 VignetteBuilder: knitr +Config/roxygen2/version: 8.1.1 diff --git a/NAMESPACE b/NAMESPACE index 3351380..74d1adb 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -9,40 +9,57 @@ export(getLm) export(getOrm) export(getTTest) export(getWilcoxonTest) -importFrom(SummarizedExperiment,assay) -importFrom(SummarizedExperiment,assayNames) -importFrom(SummarizedExperiment,colData) -importFrom(SummarizedExperiment,rowData) +importFrom(SummarizedExperiment, + assay, + assayNames, + colData, + rowData +) importFrom(broom,tidy) -importFrom(dplyr,arrange) -importFrom(dplyr,bind_rows) -importFrom(dplyr,filter) -importFrom(dplyr,group_by) -importFrom(dplyr,left_join) -importFrom(dplyr,mutate) -importFrom(dplyr,n_distinct) -importFrom(dplyr,ungroup) -importFrom(effsize,cliff.delta) -importFrom(effsize,cohen.d) -importFrom(limma,eBayes) -importFrom(limma,lmFit) -importFrom(logistf,logistf) -importFrom(logistf,logistf.control) -importFrom(rlang,"!!") -importFrom(rlang,.data) -importFrom(rlang,sym) +importFrom(dplyr, + arrange, + bind_rows, + filter, + group_by, + left_join, + mutate, + n_distinct, + ungroup +) +importFrom(effsize, + cliff.delta, + cohen.d +) +importFrom(limma, + eBayes, + lmFit +) +importFrom(logistf, + logistf, + logistf.control +) +importFrom(rlang, + "!!", + .data, + sym +) importFrom(rms,orm) -importFrom(rstatix,anova_test) -importFrom(rstatix,kruskal_test) -importFrom(rstatix,t_test) -importFrom(rstatix,wilcox_test) -importFrom(stats,as.formula) -importFrom(stats,delete.response) -importFrom(stats,lm) -importFrom(stats,model.matrix) -importFrom(stats,p.adjust) -importFrom(stats,pchisq) -importFrom(stats,terms) -importFrom(stats,var) +importFrom(rstatix, + anova_test, + kruskal_test, + t_test, + wilcox_test +) +importFrom(stats, + as.formula, + delete.response, + lm, + model.matrix, + na.omit, + p.adjust, + pchisq, + terms, + var +) importFrom(tidyr,pivot_longer) importFrom(utils,combn) diff --git a/R/getEffectSize.R b/R/getEffectSize.R index bbff905..83b1fd3 100644 --- a/R/getEffectSize.R +++ b/R/getEffectSize.R @@ -8,7 +8,8 @@ #' 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. +#' the \code{effsize} package. In paired data, Cohen's d is calculated from +#' the within-pair differences. Paired Cliff's delta is not supported. #' #' Groups are compared pairwise in the same order as in #' \code{\link{getWilcoxonTest}}. Positive values mean that values are higher @@ -20,6 +21,9 @@ #' grouping variable, e.g., \code{counts ~ Group}. #' @param method \code{Character scalar}. Effect size to calculate, #' \code{"cliff"} or \code{"cohen"}. (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}) #' @param ... Additional arguments passed to \code{effsize::cliff.delta} or #' \code{effsize::cohen.d}. #' @@ -38,71 +42,157 @@ #' \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"), + pair.by = NULL, ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE ) } method <- match.arg(method) - df <- .get_long_data(tse, formula) - res <- .calculate_effect_size(df, formula, method, ...) - return(res) + if (!is.null(pair.by) && method == "cliff") { + warning("Paired Cliff's delta is not supported; no effect size ", + "was calculated. Use method = 'cohen' for paired data.", + call. = FALSE + ) + return(NULL) + } + df <- .get_long_data(tse, formula, pair.by) + .calculate_effect_size(df, formula, method, pair.by, ...) } #' Calculate effect size for each feature and pair of groups #' #' @keywords internal #' @noRd -#' @importFrom effsize cliff.delta cohen.d +.calculate_effect_size <- function(df, formula, method, pair.by = NULL, ...) { + # Variable to test and the grouping variable from the formula + response_name <- .get_lhs(formula) + group_column <- .get_rhs(formula) + group_pairs <- .get_group_pairs(df, group_column) + # Calculate effect size separately for each feature and pair of groups + results <- lapply(split(df, df[["rownames"]]), function(feature_data) { + lapply(group_pairs, function(group_pair) { + .calculate_pair_effect_size( + feature_data, group_pair, response_name, group_column, + method, pair.by, ... + ) + }) + }) + # Flatten the nested lists (feature -> group pair) into one data.frame + results <- do.call(rbind, unlist(results, recursive = FALSE)) + rownames(results) <- NULL + 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 -.calculate_effect_size <- function(df, formula, method, ...) { - lhs <- .get_lhs(formula) - rhs <- .get_rhs(formula) - FUN <- switch(method, +.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}. +#' +#' @keywords internal +#' @noRd +#' @importFrom effsize cliff.delta cohen.d +.calculate_pair_effect_size <- function( + feature_data, group_pair, response_name, group_column, + method, pair.by, ...) { + # effsize function used for the comparison + effect_size_function <- switch(method, cliff = cliff.delta, cohen = cohen.d ) - # Pair groups in the same order as rstatix does - group <- df[[rhs]] - groups <- if (is.factor(group)) { - levels(droplevels(group)) - } else { - sort(unique(group)) + values <- .get_pair_values( + feature_data, group_pair, response_name, group_column, pair.by + ) + # Default result is NA if either group has no values, because the effect + # size cannot be calculated + effect_size <- list( + estimate = NA_real_, conf.int = c(NA_real_, NA_real_), + magnitude = NA_character_ + ) + if (length(values[["first"]]) > 0L && length(values[["second"]]) > 0L) { + # Positive effect size means group1 has higher values than group2. + # Paired data uses paired = TRUE (Cohen's d only). + effect_size <- if (is.null(pair.by)) { + effect_size_function(values[["first"]], values[["second"]], ...) + } else { + effect_size_function( + values[["first"]], values[["second"]], paired = TRUE, ... + ) + } } - if (length(groups) < 2L) { - stop("'", rhs, "' must have at least two groups.", call. = FALSE) + # One row per feature and pair of groups + data.frame( + rownames = feature_data[["rownames"]][[1L]], + group1 = group_pair[[1L]], group2 = group_pair[[2L]], + effsize = effect_size[["estimate"]] |> unname(), + conf.low = effect_size[["conf.int"]][[1L]], + conf.high = effect_size[["conf.int"]][[2L]], + magnitude = effect_size[["magnitude"]] |> as.character() + ) +} + +#' Get values of the two groups of one feature +#' +#' Unpaired: all non-missing values of each group. Paired: values aligned by +#' the pairing variable so that the i-th values of the two groups are a pair, +#' keeping only complete pairs. +#' +#' @return A list with elements \code{first} and \code{second}. +#' +#' @keywords internal +#' @noRd +#' @importFrom stats na.omit +.get_pair_values <- function( + feature_data, group_pair, response_name, group_column, pair.by) { + # Rows of the feature that belong to each of the two groups + first_group <- feature_data[ + feature_data[[group_column]] %in% group_pair[[1L]], , + drop = FALSE] + second_group <- feature_data[ + feature_data[[group_column]] %in% group_pair[[2L]], , + drop = FALSE] + first_values <- first_group[[response_name]] + second_values <- second_group[[response_name]] + if (!is.null(pair.by)) { + # Only pairing IDs present in both groups can be compared + shared_ids <- intersect( + first_group[[pair.by]], second_group[[pair.by]] + ) + # Order values by shared IDs so that the i-th values are a pair + first_values <- first_values[match(shared_ids, first_group[[pair.by]])] + second_values <- second_values[ + match(shared_ids, second_group[[pair.by]])] + # Drop pairs where either value is missing + complete <- !is.na(first_values) & !is.na(second_values) + first_values <- first_values[complete] + second_values <- second_values[complete] } - pairs <- combn(as.character(groups), 2L, simplify = FALSE) - # Calculate effect size for each feature and pair of groups - res <- lapply(split(df, df[["rownames"]]), function(feat) { - feat_res <- lapply(pairs, function(pair) { - keep <- feat[[rhs]] %in% pair & !is.na(feat[[lhs]]) - values <- feat[[lhs]][keep] - groups <- factor(feat[[rhs]][keep], levels = pair) - res <- data.frame( - rownames = feat[["rownames"]][[1L]], - group1 = pair[[1L]], - group2 = pair[[2L]], - effsize = NA_real_, - conf.low = NA_real_, - conf.high = NA_real_, - magnitude = NA_character_ - ) - # Effect size cannot be calculated if a group has no values - if (any(table(groups) == 0L)) { - return(res) - } - es <- FUN(values, groups, ...) - res[["effsize"]] <- unname(es[["estimate"]]) - res[["conf.low"]] <- es[["conf.int"]][[1L]] - res[["conf.high"]] <- es[["conf.int"]][[2L]] - res[["magnitude"]] <- as.character(es[["magnitude"]]) - return(res) - }) - do.call(rbind, feat_res) - }) - res <- do.call(rbind, res) - rownames(res) <- NULL - return(res) + # Missing values cannot be used (no-op for paired data, where incomplete + # pairs were already dropped) + list( + first = first_values |> na.omit(), + second = second_values |> na.omit() + ) } diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index 7612b5d..d70bf54 100644 --- a/R/getWilcoxonTest.R +++ b/R/getWilcoxonTest.R @@ -2,7 +2,15 @@ #' #' @description #' Performs Wilcoxon rank-sum test (Mann-Whitney U) to compare values between -#' two groups. +#' 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. +#' +#' The effect size from \code{\link{getEffectSize}} is added to the results. +#' Paired Cliff's delta is not supported. #' #' @param tse A \code{SummarizedExperiment} object. #' @param formula A formula where the LHS specifies the variable to test @@ -10,13 +18,13 @@ #' 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{NULL} or \code{Character scalar}. If -#' \code{"cliff"} or \code{"cohen"}, the effect size from -#' \code{\link{getEffectSize}} is added to the results. Not supported for -#' 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 ... Additional arguments passed to \code{wilcox_test}. #' -#' @return A \code{data.frame} with test results. +#' @return A \code{data.frame} with test results and effect size. #' #' @examples #' data(peerj13075, package = "mia") @@ -24,46 +32,36 @@ #' tse <- mia::agglomerateByRank(tse, "phylum") #' res <- getWilcoxonTest(tse, counts ~ Geographical_location) #' -#' # Add Cliff's delta +#' # Use Cohen's d instead of Cliff's delta #' res <- getWilcoxonTest( #' tse, counts ~ Geographical_location, -#' effect.size = "cliff" +#' effect.size = "cohen" #' ) #' #' @importFrom rstatix wilcox_test #' @importFrom dplyr left_join #' @export -getWilcoxonTest <- function(tse, formula, pair.by = NULL, effect.size = NULL, ...) { +getWilcoxonTest <- function( + tse, formula, pair.by = NULL, effect.size = c("cliff", "cohen"), ...) { + effect.size <- match.arg(effect.size) if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE ) } - if (!is.null(effect.size)) { - if (!is.null(pair.by)) { - stop("'effect.size' is not supported for paired tests.", - call. = FALSE - ) - } - effect.size <- match.arg(effect.size, c("cliff", "cohen")) - } df <- .get_long_data(tse, formula, pair.by) res <- .calculate_rstatix( df = df, formula = formula, pair.by = pair.by, FUN = wilcox_test, ... ) - if (!is.null(effect.size)) { - # Only groups that were tested for each feature - rhs <- .get_rhs(formula) - tested <- c( - paste(res[["rownames"]], res[["group1"]]), - paste(res[["rownames"]], res[["group2"]]) + 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 ) - df <- df[paste(df[["rownames"]], df[[rhs]]) %in% tested, , - drop = FALSE - ] - es <- .calculate_effect_size(df, formula, effect.size) - res <- left_join(res, es, by = c("rownames", "group1", "group2")) + 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/man/getEffectSize.Rd b/man/getEffectSize.Rd index a4a33f7..8b8d919 100644 --- a/man/getEffectSize.Rd +++ b/man/getEffectSize.Rd @@ -4,7 +4,7 @@ \alias{getEffectSize} \title{Calculate effect sizes between groups} \usage{ -getEffectSize(tse, formula, method = c("cliff", "cohen"), ...) +getEffectSize(tse, formula, method = c("cliff", "cohen"), pair.by = NULL, ...) } \arguments{ \item{tse}{A \code{SummarizedExperiment} object.} @@ -16,6 +16,10 @@ grouping variable, e.g., \code{counts ~ Group}.} \item{method}{\code{Character scalar}. Effect size to calculate, \code{"cliff"} or \code{"cohen"}. (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})} + \item{...}{Additional arguments passed to \code{effsize::cliff.delta} or \code{effsize::cohen.d}.} } @@ -32,7 +36,8 @@ Cohen's d. 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. +the \code{effsize} package. In paired data, Cohen's d is calculated from +the within-pair differences. Paired Cliff's delta is not supported. Groups are compared pairwise in the same order as in \code{\link{getWilcoxonTest}}. Positive values mean that values are higher diff --git a/man/getWilcoxonTest.Rd b/man/getWilcoxonTest.Rd index 56ddfc2..136d81b 100644 --- a/man/getWilcoxonTest.Rd +++ b/man/getWilcoxonTest.Rd @@ -4,7 +4,13 @@ \alias{getWilcoxonTest} \title{Perform Wilcoxon rank-sum test} \usage{ -getWilcoxonTest(tse, formula, pair.by = NULL, effect.size = NULL, ...) +getWilcoxonTest( + tse, + formula, + pair.by = NULL, + effect.size = c("cliff", "cohen"), + ... +) } \arguments{ \item{tse}{A \code{SummarizedExperiment} object.} @@ -16,19 +22,30 @@ 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{NULL} or \code{Character scalar}. If -\code{"cliff"} or \code{"cohen"}, the effect size from -\code{\link{getEffectSize}} is added to the results. Not supported for -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{...}{Additional arguments passed to \code{wilcox_test}.} } \value{ -A \code{data.frame} with test results. +A \code{data.frame} with test results and effect size. } \description{ Performs Wilcoxon rank-sum test (Mann-Whitney U) to compare values between -two groups. +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. + +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. } \examples{ data(peerj13075, package = "mia") @@ -36,8 +53,10 @@ tse <- peerj13075 tse <- mia::agglomerateByRank(tse, "phylum") res <- getWilcoxonTest(tse, counts ~ Geographical_location) -# Add Cliff's delta +# Use Cohen's d instead of Cliff's delta res <- getWilcoxonTest( - tse, counts ~ Geographical_location, effect.size = "cliff") + tse, counts ~ Geographical_location, + effect.size = "cohen" +) } diff --git a/tests/testthat/test-getEffectSize.R b/tests/testthat/test-getEffectSize.R index 684dee1..eb7827e 100644 --- a/tests/testthat/test-getEffectSize.R +++ b/tests/testthat/test-getEffectSize.R @@ -52,3 +52,130 @@ test_that("getEffectSize requires one grouping variable", { "exactly one grouping variable" ) }) + +################################################################################ +# NA handling and group checks +################################################################################ + +test_that("getEffectSize ignores missing values", { + counts <- SummarizedExperiment::assay(tse, "counts") + counts["Firmicutes", 1L] <- NA + SummarizedExperiment::assay(tse, "counts") <- counts + + res <- getEffectSize(tse, counts ~ Geographical_location) + row <- res[res$rownames == "Firmicutes" & + res$group1 == "Ahmednagar" & res$group2 == "Pune", ] + + values <- counts["Firmicutes", ] + keep <- tse$Geographical_location %in% c("Ahmednagar", "Pune") & + !is.na(values) + expected <- effsize::cliff.delta( + values[keep], + factor(tse$Geographical_location[keep], + levels = c("Ahmednagar", "Pune") + ) + ) + + expect_equal(row$effsize, unname(expected$estimate)) +}) + +test_that("getEffectSize returns NA if a group has no values", { + counts <- SummarizedExperiment::assay(tse, "counts") + counts["Firmicutes", tse$Geographical_location == "Nashik"] <- NA + SummarizedExperiment::assay(tse, "counts") <- counts + + res <- getEffectSize(tse, counts ~ Geographical_location) + firmicutes <- res[res$rownames == "Firmicutes", ] + has_nashik <- firmicutes$group1 == "Nashik" | firmicutes$group2 == "Nashik" + + expect_true(all(is.na(firmicutes$effsize[has_nashik]))) + expect_true(all(is.na(firmicutes$magnitude[has_nashik]))) + expect_false(any(is.na(firmicutes$effsize[!has_nashik]))) + # The number of rows does not depend on missing values + expect_equal(nrow(res), nrow(tse) * 3L) +}) + +test_that("getEffectSize requires at least two groups", { + one_group <- tse[, tse$Geographical_location == "Pune"] + expect_error( + getEffectSize(one_group, counts ~ Geographical_location), + "at least two groups" + ) +}) + +test_that("getEffectSize gives positive values if group1 is higher", { + counts <- SummarizedExperiment::assay(tse, "counts") + is_pune <- tse$Geographical_location == "Pune" + counts["Firmicutes", ] <- ifelse(is_pune, 1000, 1) + + seq_len(ncol(counts)) + SummarizedExperiment::assay(tse, "counts") <- counts + + res <- getEffectSize(tse, counts ~ Geographical_location) + row <- res[res$rownames == "Firmicutes" & + res$group1 == "Ahmednagar" & res$group2 == "Pune", ] + + expect_equal(row$effsize, -1) + expect_equal(row$magnitude, "large") +}) + +################################################################################ +# 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("getEffectSize calculates paired Cohen's d", { + res <- getEffectSize( + paired_tse, counts ~ Geographical_location, + method = "cohen", pair.by = "id" + ) + row <- res[res$rownames == "Firmicutes", ] + + 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 + ) + + expect_equal(nrow(res), nrow(paired_tse)) + expect_equal(row$group1, "Ahmednagar") + expect_equal(row$group2, "Nashik") + expect_equal(row$effsize, unname(expected$estimate)) + expect_equal(c(row$conf.low, row$conf.high), unname(expected$conf.int)) +}) + +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" + ) + row <- res[res$rownames == "Firmicutes", ] + + 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) + + 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 Cliff's delta is not supported" + ) + expect_null(res) +}) diff --git a/tests/testthat/test-getWilcoxonTest.R b/tests/testthat/test-getWilcoxonTest.R index bfded5c..9e73419 100644 --- a/tests/testthat/test-getWilcoxonTest.R +++ b/tests/testthat/test-getWilcoxonTest.R @@ -15,28 +15,92 @@ test_that("getWilcoxonTest with colData variable works", { expect_s3_class(res, "data.frame") }) -test_that("getWilcoxonTest adds effect sizes for each comparison", { +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 = "cliff" + effect.size = "cohen" ) - es <- getEffectSize(tse, counts ~ Geographical_location) + 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 effect sizes for paired tests", { +test_that("getWilcoxonTest rejects unknown effect sizes", { expect_error( - getWilcoxonTest( - tse, counts ~ Gender, - pair.by = "Diet", effect.size = "cliff" + getWilcoxonTest(tse, counts ~ Geographical_location, + effect.size = "other" ), - "not supported for paired tests" + "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 +) + +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", { + res <- getWilcoxonTest( + paired_tse, counts ~ Geographical_location, + pair.by = "id", effect.size = "cohen" + ) + es <- getEffectSize( + paired_tse, counts ~ Geographical_location, + method = "cohen", pair.by = "id" + ) + 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(merged$effsize.x, merged$effsize.y) +}) From 7d94c5c0ecb802a2999f3442efeca045f0b73d82 Mon Sep 17 00:00:00 2001 From: TuomasBorman Date: Tue, 1 Dec 2026 06:50:19 +0000 Subject: [PATCH 9/9] Style code (GHA) --- R/getEffectSize.R | 22 ++++++++++++---------- R/getWilcoxonTest.R | 3 +-- tests/testthat/test-getWilcoxonTest.R | 3 ++- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/R/getEffectSize.R b/R/getEffectSize.R index 83b1fd3..4044371 100644 --- a/R/getEffectSize.R +++ b/R/getEffectSize.R @@ -43,7 +43,7 @@ #' #' @export getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), - pair.by = NULL, ...) { + pair.by = NULL, ...) { if (length(all.vars(formula[[3]])) != 1L) { stop("Formula RHS must specify exactly one grouping variable.", call. = FALSE @@ -114,9 +114,8 @@ getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), #' @keywords internal #' @noRd #' @importFrom effsize cliff.delta cohen.d -.calculate_pair_effect_size <- function( - feature_data, group_pair, response_name, group_column, - method, pair.by, ...) { +.calculate_pair_effect_size <- function(feature_data, group_pair, response_name, group_column, + method, pair.by, ...) { # effsize function used for the comparison effect_size_function <- switch(method, cliff = cliff.delta, @@ -138,7 +137,8 @@ getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), effect_size_function(values[["first"]], values[["second"]], ...) } else { effect_size_function( - values[["first"]], values[["second"]], paired = TRUE, ... + values[["first"]], values[["second"]], + paired = TRUE, ... ) } } @@ -164,15 +164,16 @@ getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), #' @keywords internal #' @noRd #' @importFrom stats na.omit -.get_pair_values <- function( - feature_data, group_pair, response_name, group_column, pair.by) { +.get_pair_values <- function(feature_data, group_pair, response_name, group_column, pair.by) { # Rows of the feature that belong to each of the two groups first_group <- feature_data[ feature_data[[group_column]] %in% group_pair[[1L]], , - drop = FALSE] + drop = FALSE + ] second_group <- feature_data[ feature_data[[group_column]] %in% group_pair[[2L]], , - drop = FALSE] + drop = FALSE + ] first_values <- first_group[[response_name]] second_values <- second_group[[response_name]] if (!is.null(pair.by)) { @@ -183,7 +184,8 @@ getEffectSize <- function(tse, formula, method = c("cliff", "cohen"), # Order values by shared IDs so that the i-th values are a pair first_values <- first_values[match(shared_ids, first_group[[pair.by]])] second_values <- second_values[ - match(shared_ids, second_group[[pair.by]])] + match(shared_ids, second_group[[pair.by]]) + ] # Drop pairs where either value is missing complete <- !is.na(first_values) & !is.na(second_values) first_values <- first_values[complete] diff --git a/R/getWilcoxonTest.R b/R/getWilcoxonTest.R index d70bf54..73fdb48 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, pair.by = NULL, effect.size = c("cliff", "cohen"), ...) { +getWilcoxonTest <- function(tse, formula, pair.by = NULL, effect.size = c("cliff", "cohen"), ...) { 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/tests/testthat/test-getWilcoxonTest.R b/tests/testthat/test-getWilcoxonTest.R index 9e73419..5180918 100644 --- a/tests/testthat/test-getWilcoxonTest.R +++ b/tests/testthat/test-getWilcoxonTest.R @@ -78,7 +78,8 @@ paired_tse$id <- ave( test_that("getWilcoxonTest warns and skips paired Cliff's delta", { expect_warning( res <- getWilcoxonTest( - paired_tse, counts ~ Geographical_location, pair.by = "id" + paired_tse, counts ~ Geographical_location, + pair.by = "id" ), "Paired Cliff's delta is not supported" )