diff --git a/DESCRIPTION b/DESCRIPTION index c62fef2..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, @@ -23,13 +22,15 @@ Depends: Imports: broom, dplyr, + effsize, limma, logistf, rlang, rms, rstatix, stats, - tidyr + tidyr, + utils Suggests: mia, BiocStyle, @@ -38,3 +39,4 @@ Suggests: testthat Config/testthat/edition: 3 VignetteBuilder: knitr +Config/roxygen2/version: 8.1.1 diff --git a/NAMESPACE b/NAMESPACE index f7a4613..74d1adb 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) @@ -8,37 +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(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 new file mode 100644 index 0000000..4044371 --- /dev/null +++ b/R/getEffectSize.R @@ -0,0 +1,200 @@ +#' @title Calculate effect sizes between groups +#' +#' @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. 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 +#' 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 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}. +#' +#' @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"), + 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) + 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 +.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 +.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 + ) + 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, ... + ) + } + } + # 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] + } + # 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 0d5a141..73fdb48 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,9 +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{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") @@ -20,9 +32,17 @@ #' tse <- mia::agglomerateByRank(tse, "phylum") #' res <- getWilcoxonTest(tse, counts ~ Geographical_location) #' +#' # Use Cohen's d instead of Cliff's delta +#' res <- getWilcoxonTest( +#' tse, counts ~ Geographical_location, +#' effect.size = "cohen" +#' ) +#' #' @importFrom rstatix wilcox_test +#' @importFrom dplyr left_join #' @export -getWilcoxonTest <- function(tse, formula, pair.by = 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 @@ -33,5 +53,14 @@ getWilcoxonTest <- function(tse, formula, pair.by = NULL, ...) { df = df, formula = formula, pair.by = pair.by, FUN = wilcox_test, ... ) + if (!is.null(pair.by) && effect.size == "cliff") { + warning("Paired Cliff's delta is not supported; effect size was ", + "not calculated. Use effect.size = 'cohen' for paired data.", + call. = FALSE + ) + return(res) + } + es <- .calculate_effect_size(df, formula, effect.size, pair.by) + res <- left_join(res, es, by = c("rownames", "group1", "group2")) return(res) } diff --git a/man/getEffectSize.Rd b/man/getEffectSize.Rd new file mode 100644 index 0000000..8b8d919 --- /dev/null +++ b/man/getEffectSize.Rd @@ -0,0 +1,56 @@ +% 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"), pair.by = NULL, ...) +} +\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{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}.} +} +\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. 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 +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 0dfb710..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, ...) +getWilcoxonTest( + tse, + formula, + pair.by = NULL, + effect.size = c("cliff", "cohen"), + ... +) } \arguments{ \item{tse}{A \code{SummarizedExperiment} object.} @@ -16,14 +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{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") @@ -31,4 +53,10 @@ tse <- peerj13075 tse <- mia::agglomerateByRank(tse, "phylum") res <- getWilcoxonTest(tse, counts ~ Geographical_location) +# Use Cohen's d instead of Cliff's delta +res <- getWilcoxonTest( + tse, counts ~ Geographical_location, + effect.size = "cohen" +) + } diff --git a/tests/testthat/test-getEffectSize.R b/tests/testthat/test-getEffectSize.R new file mode 100644 index 0000000..eb7827e --- /dev/null +++ b/tests/testthat/test-getEffectSize.R @@ -0,0 +1,181 @@ +# 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" + ) +}) + +################################################################################ +# 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 fb74c18..5180918 100644 --- a/tests/testthat/test-getWilcoxonTest.R +++ b/tests/testthat/test-getWilcoxonTest.R @@ -14,3 +14,94 @@ test_that("getWilcoxonTest with colData variable works", { res <- getWilcoxonTest(tse, shannon ~ Geographical_location) expect_s3_class(res, "data.frame") }) + +effect_size_columns <- c("effsize", "conf.low", "conf.high", "magnitude") + +test_that("getWilcoxonTest adds Cliff's delta by default", { + res <- getWilcoxonTest(tse, counts ~ Geographical_location) + es <- getEffectSize(tse, counts ~ Geographical_location) + merged <- merge( + as.data.frame(res)[, c("rownames", "group1", "group2", "effsize")], + es[, c("rownames", "group1", "group2", "effsize")], + by = c("rownames", "group1", "group2") + ) + + expect_true(all(effect_size_columns %in% names(res))) + expect_equal(nrow(merged), nrow(res)) + expect_equal(merged$effsize.x, merged$effsize.y) +}) + +test_that("getWilcoxonTest has one row per feature and comparison", { + res <- getWilcoxonTest(tse, counts ~ Geographical_location) + keys <- paste(res$rownames, res$group1, res$group2) + + expect_false(anyDuplicated(keys) > 0L) + expect_false(any(is.na(res$effsize))) +}) + +test_that("getWilcoxonTest adds Cohen's d", { + res <- getWilcoxonTest( + tse, counts ~ Geographical_location, + effect.size = "cohen" + ) + es <- getEffectSize(tse, counts ~ Geographical_location, method = "cohen") + merged <- merge( + as.data.frame(res)[, c("rownames", "group1", "group2", "effsize")], + es[, c("rownames", "group1", "group2", "effsize")], + by = c("rownames", "group1", "group2") + ) + + expect_true(all(effect_size_columns %in% names(res))) + expect_equal(nrow(merged), nrow(res)) + expect_equal(merged$effsize.x, merged$effsize.y) +}) + +test_that("getWilcoxonTest rejects unknown effect sizes", { + expect_error( + getWilcoxonTest(tse, counts ~ Geographical_location, + effect.size = "other" + ), + "should be one of" + ) +}) + +################################################################################ +# Paired tests +################################################################################ + +paired_tse <- tse[, tse$Geographical_location %in% c("Ahmednagar", "Nashik")] +paired_tse$id <- ave( + seq_len(ncol(paired_tse)), paired_tse$Geographical_location, + FUN = seq_along +) + +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) +})