Skip to content
Merged
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: 2 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -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
4 changes: 4 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,29 @@

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

- title: Feature dynamics
contents:
Expand Down
101 changes: 101 additions & 0 deletions man/getRankShift.Rd

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

54 changes: 54 additions & 0 deletions tests/testthat/test-getRankShift.R
Original file line number Diff line number Diff line change
@@ -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"]])
})
28 changes: 28 additions & 0 deletions vignettes/miaTime.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading