diff --git a/NAMESPACE b/NAMESPACE index c9a40db..dbef2a3 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -7,6 +7,7 @@ export(addShortTermChange) export(addStability) export(addStepwiseDivergence) export(addSurvival) +export(addTurnover) export(getBaselineDivergence) export(getBimodality) export(getRankShift) @@ -15,6 +16,7 @@ export(getShortTermChange) export(getStability) export(getStepwiseDivergence) export(getSurvival) +export(getTurnover) exportMethods(addBaselineDivergence) exportMethods(addBimodality) exportMethods(addRankShift) @@ -22,6 +24,7 @@ exportMethods(addShortTermChange) exportMethods(addStability) exportMethods(addStepwiseDivergence) exportMethods(addSurvival) +exportMethods(addTurnover) exportMethods(getBaselineDivergence) exportMethods(getBimodality) exportMethods(getRankShift) @@ -30,6 +33,7 @@ exportMethods(getShortTermChange) exportMethods(getStability) exportMethods(getStepwiseDivergence) exportMethods(getSurvival) +exportMethods(getTurnover) import(S4Vectors) import(SingleCellExperiment) import(SummarizedExperiment) diff --git a/NEWS b/NEWS index e89d810..0cb877e 100755 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +Changes in version 1.5.x ++ Added getTurnover and addTurnover + 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..f79b964 100644 --- a/R/AllGenerics.R +++ b/R/AllGenerics.R @@ -21,6 +21,16 @@ setGeneric("getStepwiseDivergence", signature = c("x"), function(x, ...) setGeneric("addStepwiseDivergence", signature = "x", function(x, ...) standardGeneric("addStepwiseDivergence")) +#' @rdname getTurnover +#' @export +setGeneric("getTurnover", signature = "x", function(x, ...) + standardGeneric("getTurnover")) + +#' @rdname getTurnover +#' @export +setGeneric("addTurnover", signature = "x", function(x, ...) + standardGeneric("addTurnover")) + #' @rdname getBimodality #' @export setGeneric("getBimodality", signature = "x", function(x, ...) diff --git a/R/getTurnover.R b/R/getTurnover.R new file mode 100644 index 0000000..07aaa03 --- /dev/null +++ b/R/getTurnover.R @@ -0,0 +1,147 @@ +#' @name +#' getTurnover +#' +#' @export +#' +#' @title +#' Turnover of features between consecutive samples +#' +#' @description +#' Calculates the proportion of features that appear or disappear between each +#' sample and the previous sample of the same subject. +#' +#' @details +#' Turnover (Hallett et al. 2016) compares which features are present (above +#' \code{detection}) in two samples. With \eqn{G} features gained, \eqn{L} +#' features lost and \eqn{N} features present in either sample, total turnover +#' is \eqn{(G + L) / N}, appearance is \eqn{G / N} and disappearance is +#' \eqn{L / N}. The previous sample is chosen as in +#' \code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}}. +#' +#' @references +#' Hallett LM, et al. (2016) codyn: An R package of community dynamics +#' metrics. Methods in Ecology and Evolution 7(10), 1146-1151. +#' doi: 10.1111/2041-210X.12569 +#' +#' @return +#' \code{getTurnover} returns a \code{DataFrame} with one row per sample and +#' the turnover, the time from the previous sample and the previous sample. +#' \code{addTurnover} adds these to \code{colData(x)}. The first sample of each +#' subject gets \code{NA}. +#' +#' @inheritParams getStepwiseDivergence +#' +#' @param method \code{Character scalar}. The turnover to calculate: +#' \code{"total"}, \code{"appearance"} or \code{"disappearance"}. +#' (Default: \code{"total"}) +#' +#' @param detection \code{Numeric scalar}. Abundance above which a feature is +#' considered present. (Default: \code{0}) +#' +#' @param name \code{Character vector}. Specifies the names of the three +#' columns of results. (Default: \code{c("turnover", "time_diff", +#' "ref_samples")}) +#' +#' @param ... additional arguments. +#' +#' @examples +#' library(miaTime) +#' +#' # Two faecal samples of each subject in an IBD cohort +#' data(HMP_2019_ibdmdb) +#' tse <- HMP_2019_ibdmdb +#' +#' # Proportion of taxa gained since the first sample +#' tse <- addTurnover(tse, time.col = "days_from_first_collection", +#' group = "subject_id", assay.type = "relabundance", +#' method = "appearance", name = c("gained", "time_diff", "ref_samples")) +#' +#' # Proportion of taxa lost +#' tse[["lost"]] <- getTurnover(tse, time.col = "days_from_first_collection", +#' group = "subject_id", assay.type = "relabundance", +#' method = "disappearance")[["turnover"]] +#' +#' df <- as.data.frame(colData(tse)) +#' df <- df[!is.na(df[["gained"]]), ] +#' head(df[, c("subject_id", "disease_subtype", "time_diff", "gained", "lost")]) +#' +#' @seealso +#' \code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} +NULL + +#' @rdname getTurnover +#' @export +setMethod("getTurnover", signature = c(x = "SummarizedExperiment"), + function(x, time.col, assay.type = "counts", time.interval = 1L, + time.lag = NULL, group = NULL, + method = c("total", "appearance", "disappearance"), + detection = 0, ...){ + ############################# INPUT CHECK ############################## + temp <- .check_input( + time.col, list("character scalar"), colnames(colData(x))) + if( !is.numeric(x[[time.col]]) ){ + stop("'time.col' must specify numeric column from colData(x)", + call. = FALSE) + } + .check_assay_present(assay.type, x) + temp <- .check_input( + group, list(NULL, "character scalar"), colnames(colData(x))) + method <- match.arg(method) + temp <- .check_input(detection, list("numeric scalar")) + if( is.null(colnames(x)) ){ + colnames(x) <- paste0("col", seq_len(ncol(x))) + } + ########################### INPUT CHECK END ############################ + x <- .check_and_get_altExp(x, ...) + args <- .add_reference_samples_to_coldata( + x, time.col, group, time.interval = time.interval, + time.lag = time.lag, reference.method = "stepwise", ...) + present <- assay(args[["x"]], assay.type) > detection + refs <- args[["x"]][[args[["reference"]]]] + # With repeated time points, a sample has several previous samples; + # their turnovers are averaged + res <- vapply(seq_len(ncol(present)), function(j){ + r <- unlist(refs[j]) + r <- r[!is.na(r)] + if( length(r) == 0L ){ + return(NA_real_) + } + mean(vapply(r, function(k) + .turnover(present[, j], present[, k], method), numeric(1))) + }, numeric(1)) + time_res <- .get_time_difference( + args[["x"]], time.col, args[["reference"]]) + res <- .convert_divergence_to_df( + args[["x"]], res, time_res, args[["reference"]], + name = c("turnover", "time_diff", "ref_samples")) + return(res) + } +) + +#' @rdname getTurnover +#' @export +setMethod("addTurnover", signature = c(x = "SummarizedExperiment"), + function(x, name = c("turnover", "time_diff", "ref_samples"), ...){ + .check_input(name, c("character vector"), length = 3L) + res <- getTurnover(x, ...) + res <- as.list(res) |> unname() + x <- .add_values_to_colData(x, res, name, ...) + return(x) + } +) + +################################ HELP FUNCTIONS ################################ + +# Proportion of the features present in either sample that were gained, lost +# or both, from the previous sample (prev) to the current one (cur). +.turnover <- function(cur, prev, method){ + n <- sum(cur | prev) + if( n == 0L ){ + return(NA_real_) + } + changed <- switch(method, + total = cur != prev, + appearance = cur & !prev, + disappearance = !cur & prev) + return(sum(changed) / n) +} diff --git a/_pkgdown.yml b/_pkgdown.yml index f8531d1..787be89 100755 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -5,6 +5,7 @@ reference: contents: - getBaselineDivergence - getStepwiseDivergence + - getTurnover - getRankShift - title: Feature dynamics diff --git a/man/getTurnover.Rd b/man/getTurnover.Rd new file mode 100644 index 0000000..6790c0a --- /dev/null +++ b/man/getTurnover.Rd @@ -0,0 +1,114 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/AllGenerics.R, R/getTurnover.R +\name{getTurnover} +\alias{getTurnover} +\alias{addTurnover} +\alias{getTurnover,SummarizedExperiment-method} +\alias{addTurnover,SummarizedExperiment-method} +\title{Turnover of features between consecutive samples} +\usage{ +getTurnover(x, ...) + +addTurnover(x, ...) + +\S4method{getTurnover}{SummarizedExperiment}( + x, + time.col, + assay.type = "counts", + time.interval = 1L, + time.lag = NULL, + group = NULL, + method = c("total", "appearance", "disappearance"), + detection = 0, + ... +) + +\S4method{addTurnover}{SummarizedExperiment}(x, name = c("turnover", "time_diff", "ref_samples"), ...) +} +\arguments{ +\item{x}{A +\code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}} +object.} + +\item{...}{additional arguments.} + +\item{time.col}{\code{Character scalar}. Specifies a name of the column from +\code{colData} that identifies the sampling time points for the samples.} + +\item{assay.type}{\code{Character scalar}. Specifies which assay values are +used in the dissimilarity estimation. (Default: \code{"counts"})} + +\item{time.interval}{\code{Integer scalar}. Indicates the increment between +time steps. By default, the function compares each sample to the +previous one. If you need to take every second, every third, or so, time +step, then increase this accordingly. (Default: \code{1L})} + +\item{time.lag}{\code{NULL} or \code{Numeric scalar}. If specified, each +sample is compared to the earlier sample whose time is closest to +\code{time.lag} time units before it, instead of counting time steps with +\code{time.interval}. Useful when samples are not evenly spaced in time. +The first sample of each group gets \code{NA}. (Default: \code{NULL})} + +\item{group}{\code{Character scalar}. Specifies a name of the column from +\code{colData} that identifies the grouping of the samples. +(Default: \code{NULL})} + +\item{method}{\code{Character scalar}. The turnover to calculate: +\code{"total"}, \code{"appearance"} or \code{"disappearance"}. +(Default: \code{"total"})} + +\item{detection}{\code{Numeric scalar}. Abundance above which a feature is +considered present. (Default: \code{0})} + +\item{name}{\code{Character vector}. Specifies the names of the three +columns of results. (Default: \code{c("turnover", "time_diff", +"ref_samples")})} +} +\value{ +\code{getTurnover} returns a \code{DataFrame} with one row per sample and +the turnover, the time from the previous sample and the previous sample. +\code{addTurnover} adds these to \code{colData(x)}. The first sample of each +subject gets \code{NA}. +} +\description{ +Calculates the proportion of features that appear or disappear between each +sample and the previous sample of the same subject. +} +\details{ +Turnover (Hallett et al. 2016) compares which features are present (above +\code{detection}) in two samples. With \eqn{G} features gained, \eqn{L} +features lost and \eqn{N} features present in either sample, total turnover +is \eqn{(G + L) / N}, appearance is \eqn{G / N} and disappearance is +\eqn{L / N}. The previous sample is chosen as in +\code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}}. +} +\examples{ +library(miaTime) + +# Two faecal samples of each subject in an IBD cohort +data(HMP_2019_ibdmdb) +tse <- HMP_2019_ibdmdb + +# Proportion of taxa gained since the first sample +tse <- addTurnover(tse, time.col = "days_from_first_collection", + group = "subject_id", assay.type = "relabundance", + method = "appearance", name = c("gained", "time_diff", "ref_samples")) + +# Proportion of taxa lost +tse[["lost"]] <- getTurnover(tse, time.col = "days_from_first_collection", + group = "subject_id", assay.type = "relabundance", + method = "disappearance")[["turnover"]] + +df <- as.data.frame(colData(tse)) +df <- df[!is.na(df[["gained"]]), ] +head(df[, c("subject_id", "disease_subtype", "time_diff", "gained", "lost")]) + +} +\references{ +Hallett LM, et al. (2016) codyn: An R package of community dynamics +metrics. Methods in Ecology and Evolution 7(10), 1146-1151. +doi: 10.1111/2041-210X.12569 +} +\seealso{ +\code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} +} diff --git a/tests/testthat/test-getTurnover.R b/tests/testthat/test-getTurnover.R new file mode 100644 index 0000000..ca0c6f8 --- /dev/null +++ b/tests/testthat/test-getTurnover.R @@ -0,0 +1,71 @@ +data(HMP_2019_ibdmdb) +tse <- HMP_2019_ibdmdb +time <- "days_from_first_collection" + +test_that("getTurnover checks its input", { + expect_error(getTurnover(tse, time.col = "missing")) + expect_error(getTurnover(tse, time.col = "subject_id"), "numeric") + expect_error(getTurnover(tse, time.col = time, assay.type = "missing")) + expect_error(getTurnover(tse, time.col = time, + assay.type = "relabundance", method = "missing")) + expect_error(getTurnover(tse, time.col = time, + assay.type = "relabundance", detection = "a")) + expect_error(addTurnover(tse, time.col = time, + assay.type = "relabundance", name = "a")) +}) + +test_that("getTurnover equals codyn::turnover", { + # codyn::turnover() of subjects C3003 and C3005, without zero abundances + get <- function(method){ + res <- getTurnover(tse, time.col = time, group = "subject_id", + assay.type = "relabundance", method = method) + res <- res[!is.na(res[["turnover"]]), ] + res[["turnover"]][match(c("C3003", "C3005"), + tse[, rownames(res)]$subject_id)] + } + expect_equal(get("total"), c(23 / 67, 46 / 87)) + expect_equal(get("appearance"), c(12 / 67, 9 / 87)) + expect_equal(get("disappearance"), c(11 / 67, 37 / 87)) +}) + +test_that("getTurnover compares each sample with the previous one", { + res <- getTurnover(tse, time.col = time, group = "subject_id", + assay.type = "relabundance") + expect_identical(colnames(res), c("turnover", "time_diff", "ref_samples")) + expect_identical(rownames(res), colnames(tse)) + # Same reference samples as stepwise divergence + div <- getStepwiseDivergence(tse, time.col = time, group = "subject_id", + assay.type = "relabundance") + expect_identical(res[["ref_samples"]], div[["ref_samples"]]) + expect_identical(is.na(res[["turnover"]]), is.na(div[["divergence"]])) + expect_true(all(res[["turnover"]] >= 0 & res[["turnover"]] <= 1, + na.rm = TRUE)) +}) + +test_that("a higher detection threshold makes more features absent", { + res <- vapply(c(0, 0.01, 0.1), function(d) + getTurnover(tse, time.col = time, group = "subject_id", + assay.type = "relabundance", detection = d)[["turnover"]] |> + mean(na.rm = TRUE), numeric(1)) + expect_false(any(duplicated(res))) +}) + +test_that(".turnover counts gains and losses among features present", { + cur <- c(TRUE, TRUE, FALSE, FALSE) + prev <- c(TRUE, FALSE, TRUE, FALSE) + expect_equal(.turnover(cur, prev, "total"), 2 / 3) + expect_equal(.turnover(cur, prev, "appearance"), 1 / 3) + expect_equal(.turnover(cur, prev, "disappearance"), 1 / 3) + expect_equal(.turnover(cur, cur, "total"), 0) + expect_true(is.na(.turnover(c(FALSE, FALSE), c(FALSE, FALSE), "total"))) +}) + +test_that("addTurnover adds the results to colData", { + x <- addTurnover(tse, time.col = time, group = "subject_id", + assay.type = "relabundance", method = "appearance", + name = c("gained", "dt", "prev")) + expect_true(all(c("gained", "dt", "prev") %in% colnames(colData(x)))) + expect_equal(x[["gained"]], getTurnover(tse, time.col = time, + group = "subject_id", assay.type = "relabundance", + method = "appearance")[["turnover"]]) +})