diff --git a/NAMESPACE b/NAMESPACE index 74d1adb..a949010 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,6 +1,7 @@ # Generated by roxygen2: do not edit by hand export(getAnova) +export(getCorrelationTest) export(getEffectSize) export(getFirth) export(getKruskal) @@ -23,6 +24,7 @@ importFrom(dplyr, group_by, left_join, mutate, + n, n_distinct, ungroup ) @@ -45,7 +47,9 @@ importFrom(rlang, ) importFrom(rms,orm) importFrom(rstatix, + adjust_pvalue, anova_test, + cor_test, kruskal_test, t_test, wilcox_test @@ -54,10 +58,12 @@ importFrom(stats, as.formula, delete.response, lm, + lm.fit, model.matrix, na.omit, p.adjust, pchisq, + reformulate, terms, var ) diff --git a/R/getCorrelationTest.R b/R/getCorrelationTest.R new file mode 100644 index 0000000..ade00d1 --- /dev/null +++ b/R/getCorrelationTest.R @@ -0,0 +1,108 @@ +#' @title Perform correlation test +#' +#' @description +#' Performs correlation test to assess the association between values and a +#' numeric variable. +#' +#' @details +#' The test is performed separately for each feature with +#' \code{\link[rstatix:cor_test]{rstatix::cor_test}}. Only samples with values +#' for both variables (and covariates) are used. Features are tested only if +#' at least three samples remain and both variables vary. P-values are adjusted +#' for the number of features and added to column \code{p.adj}. +#' +#' If \code{adjust.by} is given, the effect of the covariates is removed first: +#' both variables are regressed on the covariates with a linear model, and the +#' correlation is calculated between the residuals. The p-values are from +#' \code{cor_test} on the residuals, so they do not account for the degrees of +#' freedom used by the covariates and are slightly optimistic. +#' +#' @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 +#' numeric variable to correlate with, e.g., \code{counts ~ shannon}. +#' @param method \code{Character scalar}. Correlation coefficient, +#' \code{"spearman"}, \code{"pearson"} or \code{"kendall"}. +#' (Default: \code{"spearman"}) +#' @param adjust.by \code{Character vector} or \code{NULL}. Names of +#' \code{colData} variables whose effect is removed before calculating the +#' correlation. (Default: \code{NULL}) +#' @param p.adjust.method \code{Character scalar}. Method passed to +#' \code{p.adjust} for multiple testing correction. (Default: \code{"BH"}) +#' @param ... Additional arguments passed to \code{cor_test}. +#' +#' @return A \code{data.frame} with test results. +#' +#' @examples +#' data(peerj13075, package = "mia") +#' tse <- peerj13075 +#' tse <- mia::agglomerateByRank(tse, "phylum") +#' tse <- mia::addAlpha(tse, index = "shannon") +#' res <- getCorrelationTest(tse, counts ~ shannon) +#' +#' # Correlation after removing the effect of covariates +#' res <- getCorrelationTest(tse, counts ~ shannon, adjust.by = "Gender") +#' +#' @importFrom rstatix cor_test adjust_pvalue +#' @importFrom rlang .data +#' @importFrom dplyr group_by filter ungroup n +#' @importFrom stats var +#' @export +getCorrelationTest <- function(tse, formula, method = c("spearman", "pearson", "kendall"), + adjust.by = NULL, p.adjust.method = "BH", ...) { + if (length(all.vars(formula[[3]])) != 1L) { + stop("Formula RHS must specify exactly one numeric variable.", + call. = FALSE + ) + } + method <- match.arg(method) + lhs <- .get_lhs(formula) + rhs <- .get_rhs(formula) + # Covariates are fetched in the same way as pairing variables + df <- .get_long_data(tse, formula, adjust.by) + if (!is.numeric(df[[rhs]])) { + stop("The independent variable must be numeric.", call. = FALSE) + } + # Only samples with values for all variables can be used + df <- df[stats::complete.cases(df[, c(lhs, rhs, adjust.by)]), , + drop = FALSE + ] + # Remove the effect of covariates from both variables + if (!is.null(adjust.by)) { + df <- .adjust_for_covariates(df, lhs, rhs, adjust.by) + } + # Feature filtering: there must be enough samples and variance in both + # variables, otherwise the correlation cannot be calculated + df <- df |> + group_by(.data[["rownames"]]) |> + filter( + n() >= 3L, + var(.data[[lhs]]) > 0, + var(.data[[rhs]]) > 0 + ) + res <- cor_test(df, vars = lhs, vars2 = rhs, method = method, ...) |> + adjust_pvalue(method = p.adjust.method) + return(res) +} + +#' Replace values by residuals after regressing out covariates +#' +#' Within each feature, both the tested variable and the numeric variable are +#' regressed on the covariates with a linear model. +#' +#' @keywords internal +#' @noRd +#' @importFrom stats lm.fit model.matrix reformulate +.adjust_for_covariates <- function(df, lhs, rhs, adjust.by) { + df <- lapply(split(df, df[["rownames"]]), function(feature_data) { + design_matrix <- model.matrix(reformulate(adjust.by), feature_data) + for (variable in c(lhs, rhs)) { + fit <- lm.fit(design_matrix, feature_data[[variable]]) + feature_data[[variable]] <- fit[["residuals"]] + } + feature_data + }) + df <- do.call(rbind, df) + rownames(df) <- NULL + return(df) +} diff --git a/man/getCorrelationTest.Rd b/man/getCorrelationTest.Rd new file mode 100644 index 0000000..e1d60bf --- /dev/null +++ b/man/getCorrelationTest.Rd @@ -0,0 +1,66 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/getCorrelationTest.R +\name{getCorrelationTest} +\alias{getCorrelationTest} +\title{Perform correlation test} +\usage{ +getCorrelationTest( + tse, + formula, + method = c("spearman", "pearson", "kendall"), + adjust.by = NULL, + p.adjust.method = "BH", + ... +) +} +\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 +numeric variable to correlate with, e.g., \code{counts ~ shannon}.} + +\item{method}{\code{Character scalar}. Correlation coefficient, +\code{"spearman"}, \code{"pearson"} or \code{"kendall"}. +(Default: \code{"spearman"})} + +\item{adjust.by}{\code{Character vector} or \code{NULL}. Names of +\code{colData} variables whose effect is removed before calculating the +correlation. (Default: \code{NULL})} + +\item{p.adjust.method}{\code{Character scalar}. Method passed to +\code{p.adjust} for multiple testing correction. (Default: \code{"BH"})} + +\item{...}{Additional arguments passed to \code{cor_test}.} +} +\value{ +A \code{data.frame} with test results. +} +\description{ +Performs correlation test to assess the association between values and a +numeric variable. +} +\details{ +The test is performed separately for each feature with +\code{\link[rstatix:cor_test]{rstatix::cor_test}}. Only samples with values +for both variables (and covariates) are used. Features are tested only if +at least three samples remain and both variables vary. P-values are adjusted +for the number of features and added to column \code{p.adj}. + +If \code{adjust.by} is given, the effect of the covariates is removed first: +both variables are regressed on the covariates with a linear model, and the +correlation is calculated between the residuals. The p-values are from +\code{cor_test} on the residuals, so they do not account for the degrees of +freedom used by the covariates and are slightly optimistic. +} +\examples{ +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +tse <- mia::addAlpha(tse, index = "shannon") +res <- getCorrelationTest(tse, counts ~ shannon) + +# Correlation after removing the effect of covariates +res <- getCorrelationTest(tse, counts ~ shannon, adjust.by = "Gender") + +} diff --git a/man/getWilcoxonTest.Rd b/man/getWilcoxonTest.Rd index 136d81b..b1a2e60 100644 --- a/man/getWilcoxonTest.Rd +++ b/man/getWilcoxonTest.Rd @@ -39,13 +39,10 @@ two groups. An effect size is added to the results. \details{ Without \code{pair.by}, the unpaired Wilcoxon rank-sum test is used. With \code{pair.by}, samples are matched and the paired signed-rank test is -used. If there are more than two groups, all pairs are compared and -p-values are adjusted. +used. If there are more than two groups, all pairs are compared. The effect size from \code{\link{getEffectSize}} is added to the results. -Paired Cliff's delta is not supported, so with \code{pair.by} use -\code{effect.size = "cohen"}; otherwise a warning is given and no effect -size is added. +Paired Cliff's delta is not supported. } \examples{ data(peerj13075, package = "mia") diff --git a/tests/testthat/test-getCorrelationTest.R b/tests/testthat/test-getCorrelationTest.R new file mode 100644 index 0000000..6a8e7e7 --- /dev/null +++ b/tests/testthat/test-getCorrelationTest.R @@ -0,0 +1,148 @@ +# Tests for getCorrelationTest +data(peerj13075, package = "mia") +tse <- peerj13075 +tse <- mia::agglomerateByRank(tse, "phylum") +tse <- mia::addAlpha(tse, index = "shannon") +# Numeric variable to correlate with +set.seed(1) +tse$score <- rnorm(ncol(tse)) + +test_that("getCorrelationTest with assay works", { + res <- getCorrelationTest(tse, counts ~ score) + expect_s3_class(res, "data.frame") + expect_true(all(c("rownames", "cor", "p", "p.adj") %in% names(res))) +}) + +test_that("getCorrelationTest with colData variable works", { + res <- getCorrelationTest(tse, shannon ~ score) + expect_s3_class(res, "data.frame") + expect_equal(nrow(res), 1L) +}) + +test_that("getCorrelationTest matches cor.test for each feature", { + res <- getCorrelationTest(tse, counts ~ score, method = "pearson") + row <- res[res$rownames == "Firmicutes", ] + + expected <- stats::cor.test( + SummarizedExperiment::assay(tse, "counts")["Firmicutes", ], + tse$score, + method = "pearson" + ) + + # rstatix rounds the correlation coefficient to two decimals + expect_equal(unname(row$cor), round(unname(expected$estimate), 2)) + expect_equal(row$p, expected$p.value) +}) + +test_that("getCorrelationTest uses Spearman correlation by default", { + res <- getCorrelationTest(tse, counts ~ score) + expect_true(all(res$method == "Spearman")) +}) + +test_that("getCorrelationTest adjusts p-values", { + res <- getCorrelationTest(tse, counts ~ score) + expect_equal(res$p.adj, stats::p.adjust(res$p, method = "BH")) + + res <- getCorrelationTest( + tse, counts ~ score, + p.adjust.method = "bonferroni" + ) + expect_equal(res$p.adj, stats::p.adjust(res$p, method = "bonferroni")) +}) + +test_that("getCorrelationTest ignores missing values", { + tse$score[1L] <- NA + res <- getCorrelationTest(tse, counts ~ score, method = "pearson") + row <- res[res$rownames == "Firmicutes", ] + + counts <- SummarizedExperiment::assay(tse, "counts")["Firmicutes", ] + keep <- !is.na(tse$score) + expected <- stats::cor.test(counts[keep], tse$score[keep]) + + expect_equal(unname(row$cor), round(unname(expected$estimate), 2)) +}) + +test_that("getCorrelationTest skips features without variance", { + counts <- SummarizedExperiment::assay(tse, "counts") + counts["Firmicutes", ] <- 1 + SummarizedExperiment::assay(tse, "counts") <- counts + + res <- getCorrelationTest(tse, counts ~ score) + expect_false("Firmicutes" %in% res$rownames) + expect_equal(nrow(res), nrow(tse) - 1L) +}) + +test_that("getCorrelationTest fails with multiple RHS vars", { + expect_error( + getCorrelationTest(tse, counts ~ score + Gender), + "exactly one" + ) +}) + +test_that("getCorrelationTest fails with non-numeric RHS", { + expect_error( + getCorrelationTest(tse, counts ~ Geographical_location), + "must be numeric" + ) +}) + +################################################################################ +# Adjustment for covariates +################################################################################ + +test_that("getCorrelationTest correlates residuals with adjust.by", { + res <- getCorrelationTest( + tse, counts ~ score, + method = "pearson", adjust.by = c("Gender", "Diet") + ) + row <- res[res$rownames == "Firmicutes", ] + + counts <- SummarizedExperiment::assay(tse, "counts")["Firmicutes", ] + counts_adjusted <- lm(counts ~ Gender + Diet, data = as.data.frame( + SummarizedExperiment::colData(tse) + )) |> residuals() + score_adjusted <- lm(score ~ Gender + Diet, data = as.data.frame( + SummarizedExperiment::colData(tse) + )) |> residuals() + expected <- stats::cor.test(counts_adjusted, score_adjusted) + + expect_equal(unname(row$cor), round(unname(expected$estimate), 2)) + expect_equal(row$p, expected$p.value) +}) + +test_that("getCorrelationTest removes the effect of a covariate", { + # Both variables depend on Gender only + set.seed(1) + is_male <- as.numeric(tse$Gender == "Male") + counts <- SummarizedExperiment::assay(tse, "counts") + counts["Firmicutes", ] <- 10 * is_male + rnorm(ncol(tse)) + SummarizedExperiment::assay(tse, "counts") <- counts + tse$score <- is_male + rnorm(ncol(tse), sd = 0.1) + + unadjusted <- getCorrelationTest(tse, counts ~ score, method = "pearson") + adjusted <- getCorrelationTest( + tse, counts ~ score, + method = "pearson", adjust.by = "Gender" + ) + + expect_gt(unadjusted[unadjusted$rownames == "Firmicutes", ]$cor, 0.9) + expect_lt(abs(adjusted[adjusted$rownames == "Firmicutes", ]$cor), 0.5) +}) + +test_that("getCorrelationTest ignores samples with missing covariates", { + tse$Gender[1L] <- NA + res <- getCorrelationTest( + tse, counts ~ score, + method = "pearson", adjust.by = "Gender" + ) + + expect_s3_class(res, "data.frame") + expect_equal(nrow(res), nrow(tse)) +}) + +test_that("getCorrelationTest fails with unknown covariate", { + expect_error( + getCorrelationTest(tse, counts ~ score, adjust.by = "nonexistent"), + "not found" + ) +}) diff --git a/vignettes/daa.Rmd b/vignettes/daa.Rmd index b807ed8..2a3a0cf 100644 --- a/vignettes/daa.Rmd +++ b/vignettes/daa.Rmd @@ -12,8 +12,8 @@ vignette: > ```{r setup, include = FALSE} knitr::opts_chunk$set( - collapse = TRUE, - comment = "#>" + collapse = TRUE, + comment = "#>" ) ``` @@ -27,7 +27,7 @@ of microbiome data. It works with `TreeSummarizedExperiment` and ```{r install, eval = FALSE} if (!requireNamespace("BiocManager", quietly = TRUE)) { - install.packages("BiocManager") + install.packages("BiocManager") } BiocManager::install("daa") @@ -93,6 +93,24 @@ res <- getWilcoxonTest(tse, shannon ~ Geographical_location) head(res) ``` +## Correlation + +The `getCorrelationTest()` function tests the correlation between feature +values and a numeric variable (Spearman by default). + +```{r correlation} +res <- getCorrelationTest(tse, counts ~ shannon) +head(res) +``` + +To remove the effect of covariates before testing, use `adjust.by`. Both +variables are regressed on the covariates and the residuals are correlated. + +```{r correlation-adjusted} +res <- getCorrelationTest(tse, counts ~ shannon, adjust.by = "Gender") +head(res) +``` + ## Wide-format methods For model-based approaches, use formula with the assay name on the LHS: