Skip to content
Open
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
4 changes: 4 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export(addShortTermChange)
export(addStability)
export(addStepwiseDivergence)
export(addSurvival)
export(addTurnover)
export(getBaselineDivergence)
export(getBimodality)
export(getRankShift)
Expand All @@ -15,13 +16,15 @@ export(getShortTermChange)
export(getStability)
export(getStepwiseDivergence)
export(getSurvival)
export(getTurnover)
exportMethods(addBaselineDivergence)
exportMethods(addBimodality)
exportMethods(addRankShift)
exportMethods(addShortTermChange)
exportMethods(addStability)
exportMethods(addStepwiseDivergence)
exportMethods(addSurvival)
exportMethods(addTurnover)
exportMethods(getBaselineDivergence)
exportMethods(getBimodality)
exportMethods(getRankShift)
Expand All @@ -30,6 +33,7 @@ exportMethods(getShortTermChange)
exportMethods(getStability)
exportMethods(getStepwiseDivergence)
exportMethods(getSurvival)
exportMethods(getTurnover)
import(S4Vectors)
import(SingleCellExperiment)
import(SummarizedExperiment)
Expand Down
3 changes: 3 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
@@ -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

Expand Down
10 changes: 10 additions & 0 deletions R/AllGenerics.R
Original file line number Diff line number Diff line change
Expand Up @@ -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, ...)
Expand Down
147 changes: 147 additions & 0 deletions R/getTurnover.R
Original file line number Diff line number Diff line change
@@ -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"]]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks too complicated. How about calculating all method = c("total", "appearance", "disappearance")at once?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Otherwise, looks good!

#'
#' 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)
}
1 change: 1 addition & 0 deletions _pkgdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ reference:
contents:
- getBaselineDivergence
- getStepwiseDivergence
- getTurnover
- getRankShift

- title: Feature dynamics
Expand Down
114 changes: 114 additions & 0 deletions man/getTurnover.Rd

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

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