diff --git a/DESCRIPTION b/DESCRIPTION index 7356bbd..b9357e2 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: miaTime Type: Package Title: Microbiome Time Series Analysis -Version: 1.5.1 +Version: 1.5.2 Authors@R: c(person(given = "Leo", family = "Lahti", role = c("aut"), email = "leo.lahti@iki.fi", @@ -52,4 +52,4 @@ BugReports: https://github.com/microbiome/miaTime/issues Encoding: UTF-8 Roxygen: list(markdown = TRUE) VignetteBuilder: knitr -Config/roxygen2/version: 8.1.0 +Config/roxygen2/version: 8.1.1 diff --git a/NAMESPACE b/NAMESPACE index 9636e2b..c9a40db 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -2,12 +2,14 @@ export(addBaselineDivergence) export(addBimodality) +export(addRankShift) export(addShortTermChange) export(addStability) export(addStepwiseDivergence) export(addSurvival) export(getBaselineDivergence) export(getBimodality) +export(getRankShift) export(getSamplingSummary) export(getShortTermChange) export(getStability) @@ -15,12 +17,14 @@ export(getStepwiseDivergence) export(getSurvival) exportMethods(addBaselineDivergence) exportMethods(addBimodality) +exportMethods(addRankShift) exportMethods(addShortTermChange) exportMethods(addStability) exportMethods(addStepwiseDivergence) exportMethods(addSurvival) exportMethods(getBaselineDivergence) exportMethods(getBimodality) +exportMethods(getRankShift) exportMethods(getSamplingSummary) exportMethods(getShortTermChange) exportMethods(getStability) diff --git a/NEWS b/NEWS index 80d63f4..e89d810 100755 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +Changes in version 1.5.2 (2026-12-03) ++ Added getRankShift and addRankShift + Changes in version 1.3.7 (2026-11-20) + getBimodality: the coefficient uses excess kurtosis, as documented in Shade et al. 2014 + Added the MovingPictures dataset diff --git a/R/AllGenerics.R b/R/AllGenerics.R index cfb760a..199ff92 100644 --- a/R/AllGenerics.R +++ b/R/AllGenerics.R @@ -65,3 +65,13 @@ setGeneric("addSurvival", signature = "x", function(x, ...) #' @export setGeneric("getSamplingSummary", signature = "x", function(x, ...) standardGeneric("getSamplingSummary")) + +#' @rdname getRankShift +#' @export +setGeneric("getRankShift", signature = "x", function(x, ...) + standardGeneric("getRankShift")) + +#' @rdname getRankShift +#' @export +setGeneric("addRankShift", signature = "x", function(x, ...) + standardGeneric("addRankShift")) diff --git a/R/getRankShift.R b/R/getRankShift.R new file mode 100644 index 0000000..8668c14 --- /dev/null +++ b/R/getRankShift.R @@ -0,0 +1,133 @@ +#' @name +#' getRankShift +#' +#' @export +#' +#' @title +#' Mean rank shift between consecutive samples +#' +#' @description +#' Calculates how much the abundance ranks of features change between each +#' sample and the previous sample of the same subject. +#' +#' @details +#' The mean rank shift (Collins et al. 2008) compares two samples through the +#' features present (above zero) in both. The features are ranked by +#' abundance in each sample, with tied values getting their average rank, and +#' the rank shift is the mean absolute change in rank. It is 0 when the order +#' of the features does not change. The previous sample is chosen as in +#' \code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}}. +#' +#' @references +#' Collins SL, et al. (2008) Rank clocks and plant community dynamics. +#' Ecology 89(12), 3534-3541. doi: 10.1890/07-1646.1 +#' +#' @return +#' \code{getRankShift} returns a \code{DataFrame} with one row per sample and +#' the rank shift, the time from the previous sample and the previous +#' sample. \code{addRankShift} adds these to \code{colData(x)}. The first +#' sample of each subject gets \code{NA}. +#' +#' @inheritParams getStepwiseDivergence +#' +#' @param name \code{Character vector}. Specifies the names of the three +#' columns of results. (Default: \code{c("rank_shift", "time_diff", +#' "ref_samples")}) +#' +#' @param ... additional arguments. +#' +#' @examples +#' library(miaTime) +#' +#' # A defined community of 16 species in three replicate bioreactors +#' data(minimalgut) +#' tse <- addRankShift(minimalgut, time.col = "Time_hr_num", +#' group = "StudyIdentifier") +#' +#' # Rank shift over time in each bioreactor; the first samples have no +#' # previous sample +#' library(miaViz) +#' plotSeries( +#' tse, +#' col.var = "rank_shift", +#' time.col = "Time_hr_num", +#' facet.by = "StudyIdentifier" +#' ) +#' +#' @seealso +#' \code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} +NULL + +#' @rdname getRankShift +#' @export +setMethod("getRankShift", signature = c(x = "SummarizedExperiment"), + function(x, time.col, assay.type = "counts", time.interval = 1L, + time.lag = NULL, group = NULL, ...){ + ############################# 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))) + 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", ...) + mat <- assay(args[["x"]], assay.type) + refs <- args[["x"]][[args[["reference"]]]] + # With repeated time points, a sample has several previous samples; + # their rank shifts are averaged + res <- vapply(seq_len(ncol(mat)), function(j){ + r <- unlist(refs[j]) + r <- r[!is.na(r)] + if( length(r) == 0L ){ + return(NA_real_) + } + mean(vapply(r, function(k) .rank_shift(mat[, j], mat[, k]), + 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("rank_shift", "time_diff", "ref_samples")) + return(res) + } +) + +#' @rdname getRankShift +#' @export +setMethod("addRankShift", signature = c(x = "SummarizedExperiment"), + function(x, name = c("rank_shift", "time_diff", "ref_samples"), ...){ + .check_input(name, c("character vector"), length = 3L) + res <- getRankShift(x, ...) + res <- as.list(res) |> unname() + x <- .add_values_to_colData(x, res, name, ...) + return(x) + } +) + +################################ HELP FUNCTIONS ################################ + +# Mean absolute change in the abundance rank of the features present in both +# samples. +.rank_shift <- function(a, b){ + present <- a > 0 & b > 0 + if( !any(present) ){ + return(NA_real_) + } + a <- a[present] + b <- b[present] + a_rank <- a |> rank() + b_rank <- b |> rank() + mean_shift <- abs(a_rank - b_rank) |> mean() + return(mean_shift) +} diff --git a/_pkgdown.yml b/_pkgdown.yml index d000a93..f8531d1 100755 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -5,6 +5,7 @@ reference: contents: - getBaselineDivergence - getStepwiseDivergence + - getRankShift - title: Feature dynamics contents: diff --git a/man/getRankShift.Rd b/man/getRankShift.Rd new file mode 100644 index 0000000..b57d383 --- /dev/null +++ b/man/getRankShift.Rd @@ -0,0 +1,101 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/AllGenerics.R, R/getRankShift.R +\name{getRankShift} +\alias{getRankShift} +\alias{addRankShift} +\alias{getRankShift,SummarizedExperiment-method} +\alias{addRankShift,SummarizedExperiment-method} +\title{Mean rank shift between consecutive samples} +\usage{ +getRankShift(x, ...) + +addRankShift(x, ...) + +\S4method{getRankShift}{SummarizedExperiment}( + x, + time.col, + assay.type = "counts", + time.interval = 1L, + time.lag = NULL, + group = NULL, + ... +) + +\S4method{addRankShift}{SummarizedExperiment}(x, name = c("rank_shift", "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{name}{\code{Character vector}. Specifies the names of the three +columns of results. (Default: \code{c("rank_shift", "time_diff", +"ref_samples")})} +} +\value{ +\code{getRankShift} returns a \code{DataFrame} with one row per sample and +the rank shift, the time from the previous sample and the previous +sample. \code{addRankShift} adds these to \code{colData(x)}. The first +sample of each subject gets \code{NA}. +} +\description{ +Calculates how much the abundance ranks of features change between each +sample and the previous sample of the same subject. +} +\details{ +The mean rank shift (Collins et al. 2008) compares two samples through the +features present (above zero) in both. The features are ranked by +abundance in each sample, with tied values getting their average rank, and +the rank shift is the mean absolute change in rank. It is 0 when the order +of the features does not change. The previous sample is chosen as in +\code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}}. +} +\examples{ +library(miaTime) + +# A defined community of 16 species in three replicate bioreactors +data(minimalgut) +tse <- addRankShift(minimalgut, time.col = "Time_hr_num", + group = "StudyIdentifier") + +# Rank shift over time in each bioreactor; the first samples have no +# previous sample +library(miaViz) +plotSeries( + tse, + col.var = "rank_shift", + time.col = "Time_hr_num", + facet.by = "StudyIdentifier" +) + +} +\references{ +Collins SL, et al. (2008) Rank clocks and plant community dynamics. +Ecology 89(12), 3534-3541. doi: 10.1890/07-1646.1 +} +\seealso{ +\code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} +} diff --git a/tests/testthat/test-getRankShift.R b/tests/testthat/test-getRankShift.R new file mode 100644 index 0000000..27c231d --- /dev/null +++ b/tests/testthat/test-getRankShift.R @@ -0,0 +1,54 @@ +data(minimalgut) +tse <- minimalgut + +test_that("getRankShift checks its input", { + expect_error(getRankShift(tse, time.col = "missing")) + expect_error(getRankShift(tse, time.col = "StudyIdentifier"), "numeric") + expect_error(getRankShift(tse, time.col = "Time_hr_num", + assay.type = "missing")) + expect_error(addRankShift(tse, time.col = "Time_hr_num", name = "a")) +}) + +test_that("getRankShift equals codyn::rank_shift", { + res <- getRankShift(tse, time.col = "Time_hr_num", + group = "StudyIdentifier") + a <- tse$StudyIdentifier == "Bioreactor A" + shift <- res[["rank_shift"]][a][order(tse$Time_hr_num[a])] + # codyn::rank_shift() of Bioreactor A, without zero abundances + expect_equal(shift[2:5], c(46, 22, 24, 18) / 15) + expect_true(is.na(shift[1L])) + expect_identical(colnames(res), c("rank_shift", "time_diff", "ref_samples")) + expect_identical(rownames(res), colnames(tse)) +}) + +test_that("getRankShift compares each sample with the previous one", { + res <- getRankShift(tse, time.col = "Time_hr_num", + group = "StudyIdentifier") + expect_equal(sum(is.na(res[["rank_shift"]])), 3L) + t0 <- tse$Time_hr_num == 0 + expect_true(all(is.na(res[["rank_shift"]][t0]))) + later <- which(!t0)[1L] + ref <- res[["ref_samples"]][later] + expect_equal(res[["time_diff"]][later], + tse$Time_hr_num[later] - tse[, ref]$Time_hr_num) + # time.lag picks the sample closest to the given lag instead + res_lag <- getRankShift(tse, time.col = "Time_hr_num", + group = "StudyIdentifier", time.lag = 24) + expect_false(identical(res_lag[["ref_samples"]], res[["ref_samples"]])) +}) + +test_that(".rank_shift is the mean absolute change in rank", { + expect_equal(.rank_shift(c(1, 2, 3), c(10, 20, 30)), 0) + expect_equal(.rank_shift(c(1, 2, 3), c(3, 2, 1)), 4 / 3) + # Features absent from either sample are left out + expect_equal(.rank_shift(c(0, 1, 2), c(5, 2, 1)), 1) + expect_true(is.na(.rank_shift(c(0, 1), c(1, 0)))) +}) + +test_that("addRankShift adds the results to colData", { + x <- addRankShift(tse, time.col = "Time_hr_num", group = "StudyIdentifier", + name = c("shift", "dt", "prev")) + expect_true(all(c("shift", "dt", "prev") %in% colnames(colData(x)))) + expect_equal(x[["shift"]], getRankShift(tse, time.col = "Time_hr_num", + group = "StudyIdentifier")[["rank_shift"]]) +}) diff --git a/vignettes/miaTime.Rmd b/vignettes/miaTime.Rmd index d748add..f4a90c3 100755 --- a/vignettes/miaTime.Rmd +++ b/vignettes/miaTime.Rmd @@ -159,6 +159,34 @@ The `time_diff` column shows how much time separates each sample from the one it is compared to. The intervals vary between subjects, which is worth keeping in mind when comparing divergences. +Divergence measures how much the composition changes, but not whether the +dominant features keep their order. The mean rank shift (Collins et al. 2008) +compares the abundance ranks of the features present in both samples. It is +zero when the order does not change. Below, we follow three bioreactors of a +synthetic gut community. + +```{r} +#| label: rank_shift + +data(minimalgut) +tse <- minimalgut + +tse <- addRankShift(tse, time.col = "Time.hr", group = "StudyIdentifier") + +plotSeries( + tse, + col.var = "rank_shift", + time.col = "Time_hr_num", + facet.by = "StudyIdentifier" +) + + geom_vline(xintercept = c(152, 248), linetype = "dashed") +``` + +The ranks change most in the first day, while the community assembles. In +all three bioreactors, they change again when a new species is added at 152 +hours and when acetate is removed from the feed at 248 hours (dashed lines), +as Shetty et al. (2022) report. + ## Short term change Short term change measures how the abundance of each feature changes between