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
7 changes: 7 additions & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,11 @@ Imports:
dplyr,
effsize,
limma,
lmerTest,
logistf,
MASS,
permute,
reformulas,
rlang,
rms,
rstatix,
Expand All @@ -35,7 +38,11 @@ Imports:
vegan
Suggests:
mia,
miaTime,
MatrixGenerics,
nlme,
BiocStyle,
DiagrammeR,
knitr,
rmarkdown,
testthat
Expand Down
27 changes: 26 additions & 1 deletion NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
# Generated by roxygen2: do not edit by hand

export(getAnova)
export(getChisqTest)
export(getCorrelationTest)
export(getDunnTest)
export(getEffectSize)
export(getFirth)
export(getFisherTest)
export(getFriedmanTest)
export(getGlm)
export(getKruskal)
export(getLeveneTest)
export(getLimma)
export(getLm)
export(getOrm)
export(getPermanova)
export(getPermdisp)
export(getShapiroTest)
export(getTTest)
export(getTukeyTest)
export(getWilcoxonTest)
importFrom(MASS,glm.nb)
importFrom(SummarizedExperiment,
assay,
assayNames,
Expand All @@ -37,11 +47,13 @@ importFrom(limma,
eBayes,
lmFit
)
importFrom(lmerTest,lmer)
importFrom(logistf,
logistf,
logistf.control
)
importFrom(permute,how)
importFrom(reformulas,findbars)
importFrom(rlang,
"!!",
.data,
Expand All @@ -51,27 +63,40 @@ importFrom(rms,orm)
importFrom(rstatix,
adjust_pvalue,
anova_test,
chisq_test,
cor_test,
dunn_test,
fisher_test,
friedman_test,
kruskal_test,
levene_test,
shapiro_test,
t_test,
tukey_hsd,
wilcox_test
)
importFrom(stats,
as.formula,
complete.cases,
delete.response,
glm,
lm,
lm.fit,
model.matrix,
na.omit,
p.adjust,
pchisq,
poisson,
reformulate,
residuals,
terms,
update,
var
)
importFrom(tidyr,pivot_longer)
importFrom(utils,combn)
importFrom(vegan,
adonis2,
betadisper,
permutest,
vegdist
)
42 changes: 42 additions & 0 deletions R/getChisqTest.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#' @title Perform chi-square test
#'
#' @description
#' Performs chi-square test to compare the prevalence (presence or absence) of
#' features between groups.
#'
#' @details
#' A feature is present in a sample if its value is higher than
#' \code{detection}. The test is performed separately for each feature using the
#' table of groups and presence. Features that are present in all samples or
#' absent in all samples are skipped. P-values are adjusted for the number of
#' features and added to column \code{p.adj}. The chi-square approximation can
#' be inaccurate if there are few samples; use \code{\link{getFisherTest}} then.
#'
#' @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 detection \code{Numeric scalar}. Values above this threshold are
#' considered present. (Default: \code{0})
#' @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{chisq_test}.
#'
#' @return A \code{data.frame} with test results.
#'
#' @examples
#' data(peerj13075, package = "mia")
#' tse <- peerj13075
#' tse <- mia::agglomerateByRank(tse, "phylum")
#' res <- getChisqTest(tse, counts ~ Geographical_location)
#'
#' @seealso \code{\link{getFisherTest}}
#'
#' @importFrom rstatix chisq_test
#' @export
getChisqTest <- function(tse, formula, detection = 0, p.adjust.method = "BH", ...) {
.calculate_contingency_test(
tse, formula, detection, p.adjust.method,
FUN = chisq_test, ...
)
}
190 changes: 152 additions & 38 deletions R/getCorrelationTest.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,19 @@
#' 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.
#' If \code{adjust.by} is given, the effect of the covariates is removed
#' first. For Spearman correlation, both variables are ranked within each
#' feature before this, so the result is the partial Spearman correlation, i.e.,
#' the Pearson correlation of the ranks after adjustment. Both variables are
#' regressed on the covariates, and the correlation is calculated between the
#' residuals. A linear model is used, or a linear mixed model if
#' \code{adjust.by} is a formula with random effects, e.g.,
#' \code{~ Gender + (1 | Subject)}. Then the residuals are what is left after
#' removing both the fixed and random effects, which is useful for repeated
#' measurements. 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. Kendall correlation is not supported with
#' \code{adjust.by}.
#'
#' @param tse A \code{SummarizedExperiment} object.
#' @param formula A formula where the LHS specifies the variable to test
Expand All @@ -24,9 +32,11 @@
#' @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 adjust.by \code{Character vector}, \code{formula} or \code{NULL}.
#' Names of \code{colData} variables whose effect is removed before
#' calculating the correlation. A formula without the LHS, e.g.,
#' \code{~ Gender + (1 | Subject)}, can include random effects.
#' (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}.
Expand All @@ -43,10 +53,6 @@
#' # 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", ...) {
Expand All @@ -56,21 +62,43 @@ getCorrelationTest <- function(tse, formula, method = c("spearman", "pearson", "
)
}
method <- match.arg(method)
if (!is.null(adjust.by)) {
if (method == "kendall") {
stop("Kendall correlation is not supported with 'adjust.by'.",
call. = FALSE
)
}
res <- .get_adjusted_correlation(
tse, formula, method, adjust.by, p.adjust.method, ...
)
} else {
res <- .get_unadjusted_correlation(
tse, formula, method, p.adjust.method, ...
)
}
return(res)
}

#' Calculate correlation without adjusting for covariates
#'
#' The data are fetched in long format, and the correlation is calculated for
#' all features with \code{cor_test}.
#'
#' @keywords internal
#' @noRd
#' @importFrom rstatix cor_test adjust_pvalue
#' @importFrom rlang .data
#' @importFrom dplyr group_by filter n
#' @importFrom stats var complete.cases
.get_unadjusted_correlation <- function(tse, formula, method, p.adjust.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)
df <- .get_long_data(tse, formula)
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)
}
# Only samples with values for both variables can be used
df <- df[complete.cases(df[, c(lhs, rhs)]), , drop = FALSE]
# Feature filtering: there must be enough samples and variance in both
# variables, otherwise the correlation cannot be calculated
df <- df |>
Expand All @@ -85,24 +113,110 @@ getCorrelationTest <- function(tse, formula, method = c("spearman", "pearson", "
return(res)
}

#' Replace values by residuals after regressing out covariates
#' Calculate correlation after adjusting for covariates
#'
#' Within each feature, both the tested variable and the numeric variable are
#' regressed on the covariates with a linear model.
#' The data are fetched in wide format, and the correlation is calculated per
#' feature with \code{.run_adjusted_correlation}.
#'
#' @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)
#' @importFrom rstatix adjust_pvalue
#' @importFrom stats reformulate
#' @importFrom SummarizedExperiment colData
.get_adjusted_correlation <- function(tse, formula, method, adjust.by, p.adjust.method, ...) {
# Covariates are given as names or as a formula, e.g., ~ Gender + (1 | ID)
adjust_formula <- if (inherits(adjust.by, "formula")) {
adjust.by
} else {
reformulate(adjust.by)
}
adjust_variables <- all.vars(adjust_formula)
if (!all(adjust_variables %in% colnames(colData(tse)))) {
stop("Covariate(s) not found in colData(x): ",
paste0("'", setdiff(adjust_variables, colnames(colData(tse))),
"'",
collapse = ", "
),
call. = FALSE
)
}
# Covariates are sample variables, fetched in the same way as pair.by
data_list <- .get_wide_data(tse, formula, adjust_variables)
if (!is.numeric(data_list[["sample_metadata"]][[.get_rhs(formula)]])) {
stop("The independent variable must be numeric.", call. = FALSE)
}
res <- .train_model_per_feature(
formula = formula,
mat = data_list[["matrix"]],
metadata = data_list[["sample_metadata"]],
FUN = .run_adjusted_correlation,
p_adjust_method = NULL,
method = method,
adjust_formula = adjust_formula,
...
) |> as.data.frame()
# Correct for the number of features
res <- adjust_pvalue(res, p.col = "p", method = p.adjust.method)
return(res)
}

#' Calculate correlation of one feature after adjusting for covariates
#'
#' @param abundance A numeric vector with a value for each sample.
#' @param metadata A \code{data.frame} of sample variables with the numeric
#' variable and the covariates.
#' @param formula The formula, e.g., \code{counts ~ score}.
#' @param method \code{"spearman"} or \code{"pearson"}.
#' @param adjust_formula Formula of the covariates, with or without random
#' effects.
#' @param ... Additional arguments passed to \code{cor_test}.
#'
#' @return A \code{data.frame} with the correlation, or \code{NULL} if it
#' cannot be calculated.
#'
#' @keywords internal
#' @noRd
#' @importFrom rstatix cor_test
#' @importFrom stats lm residuals update var complete.cases as.formula
#' @importFrom reformulas findbars
#' @importFrom lmerTest lmer
.run_adjusted_correlation <- function(abundance, metadata, formula, method, adjust_formula, ...) {
lhs <- .get_lhs(formula)
rhs <- .get_rhs(formula)
# The tested variable (.y) and the numeric variable (.x) have fixed names
# so that they cannot clash with the names of the covariates
df <- cbind.data.frame(metadata, .y = abundance)
df[[".x"]] <- df[[rhs]]
# Only samples with values for all variables can be used
df <- df[complete.cases(df[, c(".y", ".x", all.vars(adjust_formula))]), ,
drop = FALSE
]
if (nrow(df) < 3L) {
return(NULL)
}
# Partial Spearman correlation is the Pearson correlation of the ranks
if (method == "spearman") {
df[[".y"]] <- rank(df[[".y"]])
df[[".x"]] <- rank(df[[".x"]])
}
# Random effects, e.g., (1 | Subject), require a mixed model
fit_function <- if (is.null(findbars(adjust_formula))) lm else lmer
# Replace both variables by their residuals, i.e., remove the covariates
for (variable in c(".y", ".x")) {
df[[variable]] <- fit_function(
update(adjust_formula, as.formula(paste(variable, "~ ."))),
data = df
) |>
residuals() |>
unname()
}
# The correlation cannot be calculated without variance
if (var(df[[".y"]]) == 0 || var(df[[".x"]]) == 0) {
return(NULL)
}
# Ranks were already taken, so Pearson is used for Spearman as well
res <- cor_test(df, vars = ".y", vars2 = ".x", method = "pearson", ...)
res[["var1"]] <- lhs
res[["var2"]] <- rhs
return(res)
}
Loading