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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,22 @@ 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,
SummarizedExperiment
Imports:
broom,
dplyr,
effsize,
limma,
logistf,
rlang,
rms,
rstatix,
stats,
tidyr
tidyr,
utils
Suggests:
mia,
BiocStyle,
Expand All @@ -38,3 +39,4 @@ Suggests:
testthat
Config/testthat/edition: 3
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.1
83 changes: 52 additions & 31 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,44 +1,65 @@
# Generated by roxygen2: do not edit by hand

export(getAnova)
export(getEffectSize)
export(getFirth)
export(getKruskal)
export(getLimma)
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)
200 changes: 200 additions & 0 deletions R/getEffectSize.R
Original file line number Diff line number Diff line change
@@ -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()
)
}
35 changes: 32 additions & 3 deletions R/getWilcoxonTest.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,47 @@
#'
#' @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
#' (assay name, colData, or rowData variable) and the RHS specifies the
#' grouping variable, e.g., \code{counts ~ Group}.
#' @param pair.by \code{Character scalar} or \code{NULL}. Column for pairing
#' samples in paired tests. (Default: \code{NULL})
#' @param effect.size \code{Character scalar}. Effect size from
#' \code{\link{getEffectSize}} added to the results, \code{"cliff"} or
#' \code{"cohen"}. Paired Cliff's delta is not supported. (Default:
#' \code{"cliff"})
#' @param ... 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")
#' 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"
#' )
#'
#' @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
Expand All @@ -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)
}
Loading