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: 6 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Generated by roxygen2: do not edit by hand

export(getAnova)
export(getCorrelationTest)
export(getEffectSize)
export(getFirth)
export(getKruskal)
Expand All @@ -23,6 +24,7 @@ importFrom(dplyr,
group_by,
left_join,
mutate,
n,
n_distinct,
ungroup
)
Expand All @@ -45,7 +47,9 @@ importFrom(rlang,
)
importFrom(rms,orm)
importFrom(rstatix,
adjust_pvalue,
anova_test,
cor_test,
kruskal_test,
t_test,
wilcox_test
Expand All @@ -54,10 +58,12 @@ importFrom(stats,
as.formula,
delete.response,
lm,
lm.fit,
model.matrix,
na.omit,
p.adjust,
pchisq,
reformulate,
terms,
var
)
Expand Down
108 changes: 108 additions & 0 deletions R/getCorrelationTest.R
Original file line number Diff line number Diff line change
@@ -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)
}
66 changes: 66 additions & 0 deletions man/getCorrelationTest.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 2 additions & 5 deletions man/getWilcoxonTest.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

148 changes: 148 additions & 0 deletions tests/testthat/test-getCorrelationTest.R
Original file line number Diff line number Diff line change
@@ -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"
)
})
Loading
Loading