diff --git a/NAMESPACE b/NAMESPACE index c9a40db..fd46ef5 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -2,6 +2,7 @@ export(addBaselineDivergence) export(addBimodality) +export(addFeatureIndices) export(addRankShift) export(addShortTermChange) export(addStability) @@ -9,6 +10,7 @@ export(addStepwiseDivergence) export(addSurvival) export(getBaselineDivergence) export(getBimodality) +export(getFeatureIndices) export(getRankShift) export(getSamplingSummary) export(getShortTermChange) @@ -17,6 +19,7 @@ export(getStepwiseDivergence) export(getSurvival) exportMethods(addBaselineDivergence) exportMethods(addBimodality) +exportMethods(addFeatureIndices) exportMethods(addRankShift) exportMethods(addShortTermChange) exportMethods(addStability) @@ -24,6 +27,7 @@ exportMethods(addStepwiseDivergence) exportMethods(addSurvival) exportMethods(getBaselineDivergence) exportMethods(getBimodality) +exportMethods(getFeatureIndices) exportMethods(getRankShift) exportMethods(getSamplingSummary) exportMethods(getShortTermChange) diff --git a/NEWS b/NEWS index e89d810..93dba00 100755 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +Changes in version 1.5.x ++ Added getFeatureIndices and addFeatureIndices + Changes in version 1.5.2 (2026-12-03) + Added getRankShift and addRankShift diff --git a/R/AllGenerics.R b/R/AllGenerics.R index 199ff92..9d476e8 100644 --- a/R/AllGenerics.R +++ b/R/AllGenerics.R @@ -66,6 +66,16 @@ setGeneric("addSurvival", signature = "x", function(x, ...) setGeneric("getSamplingSummary", signature = "x", function(x, ...) standardGeneric("getSamplingSummary")) +#' @rdname getFeatureIndices +#' @export +setGeneric("getFeatureIndices", signature = "x", function(x, ...) + standardGeneric("getFeatureIndices")) + +#' @rdname getFeatureIndices +#' @export +setGeneric("addFeatureIndices", signature = "x", function(x, ...) + standardGeneric("addFeatureIndices")) + #' @rdname getRankShift #' @export setGeneric("getRankShift", signature = "x", function(x, ...) diff --git a/R/getBimodality.R b/R/getBimodality.R index 18e858f..c1cd4e7 100644 --- a/R/getBimodality.R +++ b/R/getBimodality.R @@ -138,7 +138,7 @@ setMethod("getBimodality", signature = c(x = "SummarizedExperiment"), if( !is.null(group) ){ res <- res |> pivot_wider( - names_from = group, + names_from = all_of(group), values_from = b ) } diff --git a/R/getFeatureIndices.R b/R/getFeatureIndices.R new file mode 100644 index 0000000..fda69e5 --- /dev/null +++ b/R/getFeatureIndices.R @@ -0,0 +1,162 @@ +#' @name +#' getFeatureIndices +#' +#' @export +#' +#' @title +#' Indices of features +#' +#' @description +#' Calculates indices that describe how the abundance of each feature varies +#' over the samples, for example over time within each subject: how much +#' (variance, coefficient of variation), in what form (skewness, kurtosis, +#' bimodality) and how persistently (stability). These are the feature-level +#' counterparts of the sample-level indices of +#' \code{\link[mia:addAlpha]{getAlpha()}}. +#' +#' @details +#' The available indices are: +#' \itemize{ +#' \item \code{"variance"}: sample variance. +#' \item \code{"cv"}: coefficient of variation, the standard deviation +#' divided by the mean. +#' \item \code{"skewness"}: moment coefficient of skewness. +#' \item \code{"kurtosis"}: moment coefficient of kurtosis (3 for a normal +#' distribution). +#' \item \code{"bimodality"}: see +#' \code{\link[miaTime:getBimodality]{getBimodality()}}. +#' \item \code{"stability"}: see +#' \code{\link[miaTime:getStability]{getStability()}}; requires +#' \code{time.col}. +#' } +#' With \code{group}, each index is calculated within each group, for example +#' within each subject, and the columns are named \code{_}. +#' +#' @return +#' \code{getFeatureIndices} returns a \code{DataFrame} with one row per feature. +#' \code{addFeatureIndices} adds the results to \code{rowData(x)}. +#' +#' @param x \code{SummarizedExperiment}. +#' +#' @param assay.type \code{Character scalar}. Specifies the name of the assay +#' used in calculation. (Default: \code{"counts"}) +#' +#' @param index \code{Character vector}. Specifies the indices to calculate. +#' (Default: \code{c("variance", "cv", "skewness", "kurtosis", +#' "bimodality")}) +#' +#' @param group \code{NULL} or \code{Character scalar}. Specifies a column +#' from \code{colData(x)} that defines the groups, for example subjects, +#' within which the indices are calculated. (Default: \code{NULL}) +#' +#' @param name \code{Character vector}. Specifies the column names for the +#' indices, one per index. (Default: \code{index}) +#' +#' @param ... additional arguments passed to +#' \code{\link[miaTime:getBimodality]{getBimodality()}} and +#' \code{\link[miaTime:getStability]{getStability()}}, such as +#' \code{time.col}. +#' +#' @examples +#' library(miaTime) +#' +#' # A defined community of 16 species in three replicate bioreactors +#' data(minimalgut) +#' tse <- transformAssay(minimalgut, method = "relabundance") +#' +#' # Indices of each species over time, within each bioreactor +#' getFeatureIndices(tse, assay.type = "relabundance", +#' index = c("cv", "stability"), group = "StudyIdentifier", +#' time.col = "Time.hr") +#' +#' # Add the indices over all samples to rowData +#' tse <- addFeatureIndices(tse, assay.type = "relabundance") +#' rowData(tse) +#' +#' @seealso +#' \code{\link[mia:addAlpha]{getAlpha()}} +NULL + +#' @rdname getFeatureIndices +#' @export +setMethod("getFeatureIndices", signature = c(x = "SummarizedExperiment"), + function(x, assay.type = "counts", index = c( + "variance", "cv", "skewness", "kurtosis", "bimodality"), + group = NULL, ...){ + .get_feature_indices(x, assay.type, index, name = index, group, ...) + } +) + +#' @rdname getFeatureIndices +#' @export +setMethod("addFeatureIndices", signature = c(x = "SummarizedExperiment"), + function(x, assay.type = "counts", index = c( + "variance", "cv", "skewness", "kurtosis", "bimodality"), + name = index, group = NULL, ...){ + x <- .check_and_get_altExp(x, ...) + res <- .get_feature_indices(x, assay.type, index, name, group, ...) + res <- as.list(res) + x <- .add_values_to_colData(x, unname(res), names(res), MARGIN = 1L) + return(x) + } +) + +################################ HELP FUNCTIONS ################################ + +# Indices that are calculated from the abundances of a feature alone. +.feature_index_functions <- list( + variance = function(v) var(v), + cv = function(v) sd(v) / mean(v), + skewness = function(v) .calculate_skewness(v), + kurtosis = function(v) .calculate_kurtosis(v) +) + +.get_feature_indices <- function(x, assay.type, index, name, group, ...){ + supported <- c(names(.feature_index_functions), "bimodality", "stability") + temp <- .check_input(index, list("character vector"), supported) + temp <- .check_input(name, list("character vector"), + length = length(index)) + if( anyDuplicated(index) ){ + stop("'index' must not include duplicates.", call. = FALSE) + } + temp <- .check_input( + group, list(NULL, "character scalar"), colnames(colData(x))) + x <- .check_and_get_altExp(x, ...) + .check_assay_present(assay.type, x) + res <- mapply(function(i, nm){ + switch(i, + bimodality = getBimodality( + x, assay.type = assay.type, group = group, name = nm, ...), + stability = getStability( + x, assay.type = assay.type, group = group, name = nm, ...), + .summarize_features( + x, assay.type, .feature_index_functions[[i]], nm, group)) + }, index, name, SIMPLIFY = FALSE) + res <- do.call(cbind, unname(res)) + return(res) +} + +# Applies FUN to the abundances of each feature, within each group. +#' @importFrom dplyr group_by across all_of summarize +#' @importFrom tidyr pivot_wider +.summarize_features <- function(x, assay.type, FUN, name, group){ + .data <- value <- NULL + df <- meltSE(x, assay.type = assay.type, add.col = group) + res <- df |> + group_by(across(all_of(c(group, "FeatureID")))) |> + summarize(value = FUN(.data[[assay.type]]), .groups = "drop") + if( !is.null(group) ){ + res <- pivot_wider(res, names_from = all_of(group), + values_from = value) + } + res <- DataFrame(res, check.names = FALSE) + rownames(res) <- res[["FeatureID"]] + res[["FeatureID"]] <- NULL + res <- res[match(rownames(x), rownames(res)), , drop = FALSE] + if( ncol(res) == 1L ){ + colnames(res) <- name + } else{ + colnames(res) <- paste0(name, "_", colnames(res)) + } + return(res) +} diff --git a/R/getStability.R b/R/getStability.R index d2b7618..8dbe18e 100644 --- a/R/getStability.R +++ b/R/getStability.R @@ -387,7 +387,7 @@ setMethod("getStability", signature = c(x = "SummarizedExperiment"), df <- df |> group_by(across(all_of(c(group, "FeatureID")))) |> pivot_wider( - names_from = group, + names_from = all_of(group), values_from = any_of(c( "stability", "stability_(<)", "stability_(>=)")) ) |> ungroup() diff --git a/_pkgdown.yml b/_pkgdown.yml index f8531d1..8f0d022 100755 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -12,6 +12,7 @@ reference: - getShortTermChange - getStability - getBimodality + - getFeatureIndices - title: Sampling contents: diff --git a/man/getFeatureIndices.Rd b/man/getFeatureIndices.Rd new file mode 100644 index 0000000..e36631f --- /dev/null +++ b/man/getFeatureIndices.Rd @@ -0,0 +1,102 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/AllGenerics.R, R/getFeatureIndices.R +\name{getFeatureIndices} +\alias{getFeatureIndices} +\alias{addFeatureIndices} +\alias{getFeatureIndices,SummarizedExperiment-method} +\alias{addFeatureIndices,SummarizedExperiment-method} +\title{Indices of features} +\usage{ +getFeatureIndices(x, ...) + +addFeatureIndices(x, ...) + +\S4method{getFeatureIndices}{SummarizedExperiment}( + x, + assay.type = "counts", + index = c("variance", "cv", "skewness", "kurtosis", "bimodality"), + group = NULL, + ... +) + +\S4method{addFeatureIndices}{SummarizedExperiment}( + x, + assay.type = "counts", + index = c("variance", "cv", "skewness", "kurtosis", "bimodality"), + name = index, + group = NULL, + ... +) +} +\arguments{ +\item{x}{\code{SummarizedExperiment}.} + +\item{...}{additional arguments passed to +\code{\link[miaTime:getBimodality]{getBimodality()}} and +\code{\link[miaTime:getStability]{getStability()}}, such as +\code{time.col}.} + +\item{assay.type}{\code{Character scalar}. Specifies the name of the assay +used in calculation. (Default: \code{"counts"})} + +\item{index}{\code{Character vector}. Specifies the indices to calculate. +(Default: \code{c("variance", "cv", "skewness", "kurtosis", +"bimodality")})} + +\item{group}{\code{NULL} or \code{Character scalar}. Specifies a column +from \code{colData(x)} that defines the groups, for example subjects, +within which the indices are calculated. (Default: \code{NULL})} + +\item{name}{\code{Character vector}. Specifies the column names for the +indices, one per index. (Default: \code{index})} +} +\value{ +\code{getFeatureIndices} returns a \code{DataFrame} with one row per feature. +\code{addFeatureIndices} adds the results to \code{rowData(x)}. +} +\description{ +Calculates indices that describe how the abundance of each feature varies +over the samples, for example over time within each subject: how much +(variance, coefficient of variation), in what form (skewness, kurtosis, +bimodality) and how persistently (stability). These are the feature-level +counterparts of the sample-level indices of +\code{\link[mia:addAlpha]{getAlpha()}}. +} +\details{ +The available indices are: +\itemize{ +\item \code{"variance"}: sample variance. +\item \code{"cv"}: coefficient of variation, the standard deviation +divided by the mean. +\item \code{"skewness"}: moment coefficient of skewness. +\item \code{"kurtosis"}: moment coefficient of kurtosis (3 for a normal +distribution). +\item \code{"bimodality"}: see +\code{\link[miaTime:getBimodality]{getBimodality()}}. +\item \code{"stability"}: see +\code{\link[miaTime:getStability]{getStability()}}; requires +\code{time.col}. +} +With \code{group}, each index is calculated within each group, for example +within each subject, and the columns are named \code{_}. +} +\examples{ +library(miaTime) + +# A defined community of 16 species in three replicate bioreactors +data(minimalgut) +tse <- transformAssay(minimalgut, method = "relabundance") + +# Indices of each species over time, within each bioreactor +getFeatureIndices(tse, assay.type = "relabundance", + index = c("cv", "stability"), group = "StudyIdentifier", + time.col = "Time.hr") + +# Add the indices over all samples to rowData +tse <- addFeatureIndices(tse, assay.type = "relabundance") +rowData(tse) + +} +\seealso{ +\code{\link[mia:addAlpha]{getAlpha()}} +} diff --git a/tests/testthat/test-getFeatureIndices.R b/tests/testthat/test-getFeatureIndices.R new file mode 100644 index 0000000..55114c9 --- /dev/null +++ b/tests/testthat/test-getFeatureIndices.R @@ -0,0 +1,56 @@ +data(minimalgut) +tse <- transformAssay(minimalgut, method = "relabundance") +m <- assay(tse, "relabundance") + +test_that("getFeatureIndices checks its input", { + expect_error(getFeatureIndices(tse, assay.type = "missing")) + expect_error(getFeatureIndices(tse, assay.type = "relabundance", + index = "missing")) + expect_error(getFeatureIndices(tse, assay.type = "relabundance", + index = c("cv", "cv")), "duplicates") + expect_error(getFeatureIndices(tse, assay.type = "relabundance", + group = "missing")) + expect_error(addFeatureIndices(tse, assay.type = "relabundance", + index = c("cv", "variance"), name = "a")) + # Stability needs the time column + expect_error(getFeatureIndices(tse, assay.type = "relabundance", + index = "stability")) +}) + +test_that("getFeatureIndices equals direct calculations", { + res <- getFeatureIndices(tse, assay.type = "relabundance") + expect_identical(colnames(res), + c("variance", "cv", "skewness", "kurtosis", "bimodality")) + expect_identical(rownames(res), rownames(tse)) + expect_equal(res[["variance"]], unname(apply(m, 1, var))) + expect_equal(res[["cv"]], unname(apply(m, 1, sd) / rowMeans(m))) + z <- (m - rowMeans(m)) / sqrt(rowMeans((m - rowMeans(m))^2)) + expect_equal(res[["skewness"]], unname(rowMeans(z^3))) + expect_equal(res[["kurtosis"]], unname(rowMeans(z^4))) + expect_equal(res[["bimodality"]], getBimodality(tse, + assay.type = "relabundance")[["bimodality"]]) +}) + +test_that("getFeatureIndices works within groups", { + res <- getFeatureIndices(tse, assay.type = "relabundance", + index = c("variance", "stability"), group = "StudyIdentifier", + time.col = "Time.hr") + groups <- unique(tse$StudyIdentifier) + expect_setequal(colnames(res), c(paste0("variance_", groups), + paste0("stability_", groups))) + a <- tse$StudyIdentifier == "Bioreactor A" + expect_equal(res[["variance_Bioreactor A"]], + unname(apply(m[, a], 1, var))) + stab <- getStability(tse, assay.type = "relabundance", + group = "StudyIdentifier", time.col = "Time.hr") + expect_equal(res[["stability_Bioreactor A"]], + stab[["stability_Bioreactor A"]]) +}) + +test_that("addFeatureIndices adds the indices to rowData", { + x <- addFeatureIndices(tse, assay.type = "relabundance", + index = c("cv", "bimodality"), name = c("cv_all", "bc")) + expect_true(all(c("cv_all", "bc") %in% colnames(rowData(x)))) + expect_equal(rowData(x)[["cv_all"]], getFeatureIndices(tse, + assay.type = "relabundance", index = "cv")[["cv"]]) +})