From cc665fde5c7aa58e318292c21ec39ac076b1c2a8 Mon Sep 17 00:00:00 2001 From: Muluh <127390183+0xMuluh@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:18:39 +0200 Subject: [PATCH 1/4] Add getRankShift --- DESCRIPTION | 2 +- NAMESPACE | 4 + NEWS | 3 + R/AllGenerics.R | 10 +++ R/getRankShift.R | 126 +++++++++++++++++++++++++++++ _pkgdown.yml | 1 + man/getRankShift.Rd | 99 +++++++++++++++++++++++ tests/testthat/test-getRankShift.R | 54 +++++++++++++ vignettes/miaTime.Rmd | 29 +++++++ 9 files changed, 327 insertions(+), 1 deletion(-) create mode 100644 R/getRankShift.R create mode 100644 man/getRankShift.Rd create mode 100644 tests/testthat/test-getRankShift.R diff --git a/DESCRIPTION b/DESCRIPTION index 35868ce..f444f21 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: miaTime Type: Package Title: Microbiome Time Series Analysis -Version: 1.3.5 +Version: 1.3.6 Authors@R: c(person(given = "Leo", family = "Lahti", role = c("aut"), email = "leo.lahti@iki.fi", 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 4f4a267..1a8f174 100755 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +Changes in version 1.3.6 (2026-11-10) ++ Added getRankShift and addRankShift + Changes in version 1.3.5 (2026-11-06) + getStepwiseDivergence: Option to select reference samples based on time lag 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..e3711a0 --- /dev/null +++ b/R/getRankShift.R @@ -0,0 +1,126 @@ +#' @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(ggplot2) +#' df <- as.data.frame(colData(tse)) +#' df <- df[!is.na(df[["rank_shift"]]), ] +#' ggplot(df, aes(x = Time_hr_num, y = rank_shift, colour = StudyIdentifier)) + +#' geom_line() +#' +#' @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_) + } + return(mean(abs(rank(a[present]) - rank(b[present])))) +} diff --git a/_pkgdown.yml b/_pkgdown.yml index 2649e2b..83b54cc 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..069606e --- /dev/null +++ b/man/getRankShift.Rd @@ -0,0 +1,99 @@ +% 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(ggplot2) +df <- as.data.frame(colData(tse)) +df <- df[!is.na(df[["rank_shift"]]), ] +ggplot(df, aes(x = Time_hr_num, y = rank_shift, colour = StudyIdentifier)) + + geom_line() + +} +\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..6c3eaac 100755 --- a/vignettes/miaTime.Rmd +++ b/vignettes/miaTime.Rmd @@ -159,6 +159,35 @@ 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") + +# The first sample of each bioreactor has no previous sample +df <- as.data.frame(colData(tse)) +df <- df[!is.na(df[["rank_shift"]]), ] + +ggplot(df, aes(x = Time.hr, y = rank_shift, colour = StudyIdentifier)) + + geom_line() + + geom_vline(xintercept = c(152, 248), linetype = "dashed") + + labs(x = "Time (h)", y = "Mean rank shift", colour = "Bioreactor") +``` + +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 From 5b894811ab2bd0f5c64cdbbe49d2bd0a2949a269 Mon Sep 17 00:00:00 2001 From: Tuomas Borman Date: Thu, 3 Dec 2026 09:24:54 +0200 Subject: [PATCH 2/4] up --- DESCRIPTION | 2 +- R/getRankShift.R | 19 +++++++++++++------ man/getRankShift.Rd | 12 +++++++----- vignettes/miaTime.Rmd | 14 ++++++-------- 4 files changed, 27 insertions(+), 20 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 7356bbd..2b989d4 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -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/R/getRankShift.R b/R/getRankShift.R index e3711a0..8668c14 100644 --- a/R/getRankShift.R +++ b/R/getRankShift.R @@ -46,11 +46,13 @@ #' #' # Rank shift over time in each bioreactor; the first samples have no #' # previous sample -#' library(ggplot2) -#' df <- as.data.frame(colData(tse)) -#' df <- df[!is.na(df[["rank_shift"]]), ] -#' ggplot(df, aes(x = Time_hr_num, y = rank_shift, colour = StudyIdentifier)) + -#' geom_line() +#' library(miaViz) +#' plotSeries( +#' tse, +#' col.var = "rank_shift", +#' time.col = "Time_hr_num", +#' facet.by = "StudyIdentifier" +#' ) #' #' @seealso #' \code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} @@ -122,5 +124,10 @@ setMethod("addRankShift", signature = c(x = "SummarizedExperiment"), if( !any(present) ){ return(NA_real_) } - return(mean(abs(rank(a[present]) - rank(b[present])))) + 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/man/getRankShift.Rd b/man/getRankShift.Rd index 069606e..b57d383 100644 --- a/man/getRankShift.Rd +++ b/man/getRankShift.Rd @@ -83,11 +83,13 @@ tse <- addRankShift(minimalgut, time.col = "Time_hr_num", # Rank shift over time in each bioreactor; the first samples have no # previous sample -library(ggplot2) -df <- as.data.frame(colData(tse)) -df <- df[!is.na(df[["rank_shift"]]), ] -ggplot(df, aes(x = Time_hr_num, y = rank_shift, colour = StudyIdentifier)) + - geom_line() +library(miaViz) +plotSeries( + tse, + col.var = "rank_shift", + time.col = "Time_hr_num", + facet.by = "StudyIdentifier" +) } \references{ diff --git a/vignettes/miaTime.Rmd b/vignettes/miaTime.Rmd index 6c3eaac..25b2e67 100755 --- a/vignettes/miaTime.Rmd +++ b/vignettes/miaTime.Rmd @@ -173,14 +173,12 @@ tse <- minimalgut tse <- addRankShift(tse, time.col = "Time.hr", group = "StudyIdentifier") -# The first sample of each bioreactor has no previous sample -df <- as.data.frame(colData(tse)) -df <- df[!is.na(df[["rank_shift"]]), ] - -ggplot(df, aes(x = Time.hr, y = rank_shift, colour = StudyIdentifier)) + - geom_line() + - geom_vline(xintercept = c(152, 248), linetype = "dashed") + - labs(x = "Time (h)", y = "Mean rank shift", colour = "Bioreactor") +plotSeries( + tse, + col.var = "rank_shift", + time.col = "Time_hr_num", + facet.by = "StudyIdentifier" +) ``` The ranks change most in the first day, while the community assembles. In From 2119e0de491506bfd781f3760819d8db3cce6bb6 Mon Sep 17 00:00:00 2001 From: Tuomas Borman Date: Thu, 3 Dec 2026 09:28:28 +0200 Subject: [PATCH 3/4] up --- DESCRIPTION | 2 +- NEWS | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 2b989d4..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", diff --git a/NEWS b/NEWS index d394117..e89d810 100755 --- a/NEWS +++ b/NEWS @@ -1,4 +1,4 @@ -Changes in version 1.5.x +Changes in version 1.5.2 (2026-12-03) + Added getRankShift and addRankShift Changes in version 1.3.7 (2026-11-20) From d43dea516b018f54b1a53922bdb0e9cf217ed5cc Mon Sep 17 00:00:00 2001 From: Tuomas Borman Date: Thu, 3 Dec 2026 09:30:07 +0200 Subject: [PATCH 4/4] up --- vignettes/miaTime.Rmd | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/vignettes/miaTime.Rmd b/vignettes/miaTime.Rmd index 25b2e67..f4a90c3 100755 --- a/vignettes/miaTime.Rmd +++ b/vignettes/miaTime.Rmd @@ -178,7 +178,8 @@ plotSeries( 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