From abcebbd95694831a4c27d0bd606237b30c0c248d Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Tue, 10 Nov 2026 14:01:53 +0200 Subject: [PATCH 1/2] Rename getSurvival to getCox --- DESCRIPTION | 2 +- NAMESPACE | 8 +- NEWS | 3 + R/AllGenerics.R | 12 +-- R/{getSurvival.R => getCox.R} | 72 +++++++++++------ _pkgdown.yml | 2 +- man/{getSurvival.Rd => getCox.Rd} | 63 ++++++++++----- .../{test-getSurvival.R => test-getCox.R} | 78 +++++++++---------- 8 files changed, 147 insertions(+), 93 deletions(-) rename R/{getSurvival.R => getCox.R} (86%) rename man/{getSurvival.Rd => getCox.Rd} (70%) rename tests/testthat/{test-getSurvival.R => test-getCox.R} (87%) 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..f8f5b0d 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -2,30 +2,30 @@ export(addBaselineDivergence) export(addBimodality) +export(addCox) export(addShortTermChange) export(addStability) export(addStepwiseDivergence) -export(addSurvival) export(getBaselineDivergence) export(getBimodality) +export(getCox) export(getSamplingSummary) export(getShortTermChange) export(getStability) export(getStepwiseDivergence) -export(getSurvival) exportMethods(addBaselineDivergence) exportMethods(addBimodality) +exportMethods(addCox) exportMethods(addShortTermChange) exportMethods(addStability) exportMethods(addStepwiseDivergence) -exportMethods(addSurvival) exportMethods(getBaselineDivergence) exportMethods(getBimodality) +exportMethods(getCox) exportMethods(getSamplingSummary) exportMethods(getShortTermChange) exportMethods(getStability) exportMethods(getStepwiseDivergence) -exportMethods(getSurvival) import(S4Vectors) import(SingleCellExperiment) import(SummarizedExperiment) diff --git a/NEWS b/NEWS index 4f4a267..41c4327 100755 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +Changes in version 1.3.6 (2026-11-10) ++ Renamed getSurvival and addSurvival to getCox and addCox, and nvar to max.features; added examples that summarise and plot the results + 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..0e64f17 100644 --- a/R/AllGenerics.R +++ b/R/AllGenerics.R @@ -51,15 +51,15 @@ setGeneric("getStability", signature = "x", function(x, ...) setGeneric("addStability", signature = "x", function(x, ...) standardGeneric("addStability")) -#' @rdname getSurvival +#' @rdname getCox #' @export -setGeneric("getSurvival", signature = "x", function(x, ...) - standardGeneric("getSurvival")) +setGeneric("getCox", signature = "x", function(x, ...) + standardGeneric("getCox")) -#' @rdname getSurvival +#' @rdname getCox #' @export -setGeneric("addSurvival", signature = "x", function(x, ...) - standardGeneric("addSurvival")) +setGeneric("addCox", signature = "x", function(x, ...) + standardGeneric("addCox")) #' @rdname getSamplingSummary #' @export diff --git a/R/getSurvival.R b/R/getCox.R similarity index 86% rename from R/getSurvival.R rename to R/getCox.R index 63febdc..06417d8 100644 --- a/R/getSurvival.R +++ b/R/getCox.R @@ -1,5 +1,5 @@ #' @name -#' getSurvival +#' getCox #' #' @export #' @@ -13,7 +13,7 @@ #' (e.g. with \code{mia::transformAssay()}). #' #' @details -#' \code{getSurvival()} fits a Cox proportional hazards model with the +#' \code{getCox()} fits a Cox proportional hazards model with the #' features of \code{assay.type} as predictors. By default #' (\code{penalized = TRUE}), an elastic net penalized model is fitted with #' \code{glmnet::cv.glmnet()}, and the penalty is selected by @@ -37,7 +37,7 @@ #' available from \code{fit}. Risk scores and C-index are calculated from the #' fitted model and are not affected by the rescaling. #' -#' \code{addSurvival()} adds the coefficients to \code{rowData} (\code{NA} +#' \code{addCox()} adds the coefficients to \code{rowData} (\code{NA} #' for features not in the model), the risk scores to \code{colData}, and the #' full results to \code{metadata}. #' @@ -72,8 +72,9 @@ #' \item \code{nfolds}: \code{Integer scalar}. Number of cross-validation #' folds for \code{cv.glmnet}. (Default: \code{10}) #' -#' \item \code{nvar}: \code{Integer scalar}. Optional. Maximum number of -#' variables (log-ratios) to include in the model. (Default: \code{NULL}) +#' \item \code{max.features}: \code{Integer scalar}. Optional. Maximum +#' number of features (log-ratios) to include in the model. +#' (Default: \code{NULL}) #' #' \item \code{coef.threshold}: \code{Numeric scalar}. Minimum absolute value #' for a coefficient to be included in the final model. (Default: \code{0}) @@ -82,11 +83,11 @@ #' @param name \code{Character vector} of length 3. Names for the #' coefficients in \code{rowData}, the risk scores in \code{colData} and the #' full results in \code{metadata}. -#' (Default: \code{c("survival_coef", "survival_risk_score", "survival")}) +#' (Default: \code{c("cox_coef", "cox_risk_score", "cox")}) #' #' @inheritParams addBaselineDivergence #' -#' @return \code{getSurvival()} returns a list with model summaries: +#' @return \code{getCox()} returns a list with model summaries: #' \itemize{ #' \item \code{coef}: estimated model coefficients #' \item \code{risk_scores}: predicted risk scores @@ -95,7 +96,7 @@ #' \item \code{c_index_cv_sd}: SD of cross-validated C-index (if penalized) #' \item \code{fit}: fitted model object (coxph or cv.glmnet) #' } -#' \code{addSurvival()} returns \code{x} with the results added. +#' \code{addCox()} returns \code{x} with the results added. #' #' @seealso \code{\link[coda4microbiome]{coda_coxnet}}, #' \code{\link[glmnet]{cv.glmnet}} @@ -110,26 +111,50 @@ #' data(crohn_survival) #' tse <- crohn_survival #' tse <- transformAssay(tse, method = "relabundance") -#' fit <- getSurvival( +#' set.seed(1) +#' tse <- addCox( #' tse, assay.type = "relabundance", #' time.col = "event_time", event.col = "event" #' ) #' +#' # Features in the model, by coefficient, and the concordance index +#' coefs <- rowData(tse)[["cox_coef"]] +#' names(coefs) <- rownames(tse) +#' coefs <- sort(coefs[!is.na(coefs) & coefs != 0]) +#' data.frame(feature = names(coefs), coefficient = unname(coefs)) +#' metadata(tse)[["cox"]][["c_index"]] +#' +#' # The coefficients +#' op <- par(mar = c(4, 14, 1, 1)) +#' barplot(coefs, horiz = TRUE, las = 1, xlab = "Coefficient") +#' par(op) +#' +#' # Time to event of samples with risk scores above and below the median; +#' # the scores come from the data the model was fitted to, so the separation +#' # is optimistic +#' df <- data.frame(time = tse$event_time, event = tse$event, +#' risk = ifelse(tse$cox_risk_score > median(tse$cox_risk_score), +#' "high", "low")) +#' km <- survival::survfit(survival::Surv(time, event) ~ risk, data = df) +#' plot(km, col = c("red", "blue"), xlab = "Time", ylab = "Without event") +#' legend("bottomleft", legend = c("high risk", "low risk"), +#' col = c("red", "blue"), lty = 1) +#' NULL -#' @rdname getSurvival +#' @rdname getCox #' @export -setMethod("addSurvival", signature = c(x = "SummarizedExperiment"), +setMethod("addCox", signature = c(x = "SummarizedExperiment"), function( x, time.col, event.col, - name = c("survival_coef", "survival_risk_score", "survival"), ...){ + name = c("cox_coef", "cox_risk_score", "cox"), ...){ .check_input(name, "character vector", length = 3L) x <- .check_and_get_altExp(x, ...) # Run analysis args <- c( list(x = x, time.col = time.col, event.col = event.col), list(...)[!names(list(...)) %in% c("altexp")]) - res <- do.call(getSurvival, args) + res <- do.call(getCox, args) # Add feature coefficients to rowData. Features that are not in the # model get NA. coefs <- unname(res[["coef"]][rownames(x)]) @@ -142,9 +167,9 @@ setMethod("addSurvival", signature = c(x = "SummarizedExperiment"), } ) -#' @rdname getSurvival +#' @rdname getCox #' @export -setMethod("getSurvival", signature(x = "SummarizedExperiment"), +setMethod("getCox", signature(x = "SummarizedExperiment"), function(x, time.col, event.col, assay.type = "counts", col.var = NULL, ...){ # Input checks @@ -271,9 +296,9 @@ setMethod("getSurvival", signature(x = "SummarizedExperiment"), offset = offset ) - # Select lambda value based on user input and optional nvar constraint to - # allow selecting lambda that balances model sparsity and predictive - # performance + # Select lambda value based on user input and optional max.features + # constraint to allow selecting lambda that balances model sparsity and + # predictive performance lambda_value <- .lambda_selector(fit, lambda, ...) # Extract coefficients at chosen lambda coefs <- coef(fit, s = lambda_value) @@ -381,11 +406,12 @@ setMethod("getSurvival", signature(x = "SummarizedExperiment"), # # Allows choosing lambda based on CV results or restricting the model to a # maximum number of variables. -.lambda_selector <- function(fit, lambda, nvar = NULL, ...) { - # Handle nvar cutoff - if( !is.null(nvar) ){ - # Identify lambda values with number of non-zero coefficients <= nvar. - valid <- which(fit[["glmnet.fit"]][["df"]] <= nvar) +.lambda_selector <- function(fit, lambda, max.features = NULL, ...) { + # Handle max.features cutoff + if( !is.null(max.features) ){ + # Identify lambda values with at most max.features non-zero + # coefficients. + valid <- which(fit[["glmnet.fit"]][["df"]] <= max.features) # If such lambdas exist, choose the lambda for model that has # highest number of taxa. if( length(valid) > 0L ){ diff --git a/_pkgdown.yml b/_pkgdown.yml index 2649e2b..7d60ddb 100755 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -18,7 +18,7 @@ reference: - title: Survival contents: - - getSurvival + - getCox - title: Datasets contents: diff --git a/man/getSurvival.Rd b/man/getCox.Rd similarity index 70% rename from man/getSurvival.Rd rename to man/getCox.Rd index ae26c80..7421249 100644 --- a/man/getSurvival.Rd +++ b/man/getCox.Rd @@ -1,25 +1,25 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/AllGenerics.R, R/getSurvival.R -\name{getSurvival} -\alias{getSurvival} -\alias{addSurvival} -\alias{addSurvival,SummarizedExperiment-method} -\alias{getSurvival,SummarizedExperiment-method} +% Please edit documentation in R/AllGenerics.R, R/getCox.R +\name{getCox} +\alias{getCox} +\alias{addCox} +\alias{addCox,SummarizedExperiment-method} +\alias{getCox,SummarizedExperiment-method} \title{Survival analysis} \usage{ -getSurvival(x, ...) +getCox(x, ...) -addSurvival(x, ...) +addCox(x, ...) -\S4method{addSurvival}{SummarizedExperiment}( +\S4method{addCox}{SummarizedExperiment}( x, time.col, event.col, - name = c("survival_coef", "survival_risk_score", "survival"), + name = c("cox_coef", "cox_risk_score", "cox"), ... ) -\S4method{getSurvival}{SummarizedExperiment}(x, time.col, event.col, assay.type = "counts", col.var = NULL, ...) +\S4method{getCox}{SummarizedExperiment}(x, time.col, event.col, assay.type = "counts", col.var = NULL, ...) } \arguments{ \item{x}{A @@ -46,8 +46,9 @@ Values between 0 and 1 specify a combination of the two. \item \code{nfolds}: \code{Integer scalar}. Number of cross-validation folds for \code{cv.glmnet}. (Default: \code{10}) -\item \code{nvar}: \code{Integer scalar}. Optional. Maximum number of -variables (log-ratios) to include in the model. (Default: \code{NULL}) +\item \code{max.features}: \code{Integer scalar}. Optional. Maximum +number of features (log-ratios) to include in the model. +(Default: \code{NULL}) \item \code{coef.threshold}: \code{Numeric scalar}. Minimum absolute value for a coefficient to be included in the final model. (Default: \code{0}) @@ -63,7 +64,7 @@ logical (\code{TRUE}/\code{FALSE}) values.} \item{name}{\code{Character vector} of length 3. Names for the coefficients in \code{rowData}, the risk scores in \code{colData} and the full results in \code{metadata}. -(Default: \code{c("survival_coef", "survival_risk_score", "survival")})} +(Default: \code{c("cox_coef", "cox_risk_score", "cox")})} \item{assay.type}{\code{Character scalar}. Specifies which assay values are used in the dissimilarity estimation. (Default: \code{"counts"})} @@ -73,7 +74,7 @@ columns in \code{colData(x)} to adjust for in the survival model. (Default: \code{NULL})} } \value{ -\code{getSurvival()} returns a list with model summaries: +\code{getCox()} returns a list with model summaries: \itemize{ \item \code{coef}: estimated model coefficients \item \code{risk_scores}: predicted risk scores @@ -82,7 +83,7 @@ columns in \code{colData(x)} to adjust for in the survival model. \item \code{c_index_cv_sd}: SD of cross-validated C-index (if penalized) \item \code{fit}: fitted model object (coxph or cv.glmnet) } -\code{addSurvival()} returns \code{x} with the results added. +\code{addCox()} returns \code{x} with the results added. } \description{ Fit a (penalized) Cox proportional hazards model on microbiome data contained @@ -91,7 +92,7 @@ log-ratios) should be handled upstream (e.g. with \code{mia::transformAssay()}). } \details{ -\code{getSurvival()} fits a Cox proportional hazards model with the +\code{getCox()} fits a Cox proportional hazards model with the features of \code{assay.type} as predictors. By default (\code{penalized = TRUE}), an elastic net penalized model is fitted with \code{glmnet::cv.glmnet()}, and the penalty is selected by @@ -115,7 +116,7 @@ feature, but they are not log hazard ratios. The unscaled coefficients are available from \code{fit}. Risk scores and C-index are calculated from the fitted model and are not affected by the rescaling. -\code{addSurvival()} adds the coefficients to \code{rowData} (\code{NA} +\code{addCox()} adds the coefficients to \code{rowData} (\code{NA} for features not in the model), the risk scores to \code{colData}, and the full results to \code{metadata}. } @@ -123,11 +124,35 @@ full results to \code{metadata}. data(crohn_survival) tse <- crohn_survival tse <- transformAssay(tse, method = "relabundance") -fit <- getSurvival( +set.seed(1) +tse <- addCox( tse, assay.type = "relabundance", time.col = "event_time", event.col = "event" ) +# Features in the model, by coefficient, and the concordance index +coefs <- rowData(tse)[["cox_coef"]] +names(coefs) <- rownames(tse) +coefs <- sort(coefs[!is.na(coefs) & coefs != 0]) +data.frame(feature = names(coefs), coefficient = unname(coefs)) +metadata(tse)[["cox"]][["c_index"]] + +# The coefficients +op <- par(mar = c(4, 14, 1, 1)) +barplot(coefs, horiz = TRUE, las = 1, xlab = "Coefficient") +par(op) + +# Time to event of samples with risk scores above and below the median; +# the scores come from the data the model was fitted to, so the separation +# is optimistic +df <- data.frame(time = tse$event_time, event = tse$event, + risk = ifelse(tse$cox_risk_score > median(tse$cox_risk_score), + "high", "low")) +km <- survival::survfit(survival::Surv(time, event) ~ risk, data = df) +plot(km, col = c("red", "blue"), xlab = "Time", ylab = "Without event") +legend("bottomleft", legend = c("high risk", "low risk"), + col = c("red", "blue"), lty = 1) + } \references{ Meritxell Pujolassos , Antoni Susín , M.Luz Calle (2024). diff --git a/tests/testthat/test-getSurvival.R b/tests/testthat/test-getCox.R similarity index 87% rename from tests/testthat/test-getSurvival.R rename to tests/testthat/test-getCox.R index 0094461..84bf67e 100644 --- a/tests/testthat/test-getSurvival.R +++ b/tests/testthat/test-getCox.R @@ -1,5 +1,5 @@ # Check that input checks work -test_that("getSurvival validates input", { +test_that("getCox validates input", { # Load and prepare data data(crohn_survival) tse <- crohn_survival @@ -7,7 +7,7 @@ test_that("getSurvival validates input", { # Test that function works with valid inputs expect_no_error({ - fit <- getSurvival( + fit <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -16,20 +16,20 @@ test_that("getSurvival validates input", { }) expect_error({ - getSurvival( + getCox( tse, assay.type = "relabundance" ) }) expect_error({ - getSurvival( + getCox( tse ) }) # Test error with non-existent time column expect_error({ - getSurvival( + getCox( tse, assay.type = "relabundance", time.col = "nonexistent_time", @@ -38,7 +38,7 @@ test_that("getSurvival validates input", { }) expect_error({ - getSurvival( + getCox( tse, assay.type = "relabundance", event.col = "event" @@ -47,7 +47,7 @@ test_that("getSurvival validates input", { # Test error with non-existent event column expect_error({ - getSurvival( + getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -56,7 +56,7 @@ test_that("getSurvival validates input", { }) expect_error({ - getSurvival( + getCox( tse, assay.type = "relabundance", time.col = "event_time" @@ -65,7 +65,7 @@ test_that("getSurvival validates input", { # Test error with non-existent assay expect_error({ - getSurvival( + getCox( tse, assay.type = "nonexistent_assay", time.col = "event_time", @@ -75,7 +75,7 @@ test_that("getSurvival validates input", { }) # Check that method works correctly -test_that("getSurvival works correctly", { +test_that("getCox works correctly", { # Load the example data data(crohn_survival) tse <- crohn_survival @@ -90,8 +90,8 @@ test_that("getSurvival works correctly", { # Transform to relative abundance as in example tse <- transformAssay(tse, method = "relabundance") - # Test basic getSurvival functionality - fit <- getSurvival( + # Test basic getCox functionality + fit <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -127,14 +127,14 @@ test_that("getSurvival works correctly", { }) # Check that method handles different params passed in ... -test_that("getSurvival handles different parameters", { +test_that("getCox handles different parameters", { # Load and prepare data data(crohn_survival) tse <- crohn_survival tse <- transformAssay(tse, method = "relabundance") # Test with different alpha values - fit_ridge <- getSurvival( + fit_ridge <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -142,7 +142,7 @@ test_that("getSurvival handles different parameters", { alpha = 0.1 # Ridge regression ) - fit_lasso <- getSurvival( + fit_lasso <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -159,7 +159,7 @@ test_that("getSurvival handles different parameters", { expect_false(identical(fit_ridge$risk_scores, fit_lasso$risk_scores)) # Test with standard Cox regression (no penalization) - fit_standard <- getSurvival( + fit_standard <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -176,7 +176,7 @@ test_that("getSurvival handles different parameters", { }) # Check that method handles covariates -test_that("getSurvival handles covariates", { +test_that("getCox handles covariates", { # Load and prepare data data(crohn_survival) tse <- crohn_survival @@ -192,7 +192,7 @@ test_that("getSurvival handles covariates", { colData(tse)$sex <- factor(sample(c("M", "F"), n, replace = TRUE)) # Test with available covariates (use first available column) - fit_with_covs <- getSurvival( + fit_with_covs <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -201,7 +201,7 @@ test_that("getSurvival handles covariates", { ) # Test without covariates for comparison - fit_without_covs <- getSurvival( + fit_without_covs <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -222,7 +222,7 @@ test_that("getSurvival handles covariates", { }) # Check that method handles coefficient filtering -test_that("getSurvival handles coefficient filtering", { +test_that("getCox handles coefficient filtering", { # Load and prepare data data(crohn_survival) tse <- crohn_survival @@ -231,7 +231,7 @@ test_that("getSurvival handles coefficient filtering", { # Test with different coefficient thresholds. Use the same seed so that # cross-validation folds are the same. set.seed(1) - fit_no_filter <- getSurvival( + fit_no_filter <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -240,7 +240,7 @@ test_that("getSurvival handles coefficient filtering", { ) set.seed(1) - fit_filtered <- getSurvival( + fit_filtered <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -257,7 +257,7 @@ test_that("getSurvival handles coefficient filtering", { } # Test with high threshold that might filter out all coefficients - fit_high_filter <- getSurvival( + fit_high_filter <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -271,13 +271,13 @@ test_that("getSurvival handles coefficient filtering", { }) # Check that method handles different transformations -test_that("getSurvival handles different assay types", { +test_that("getCox handles different assay types", { # Load data data(crohn_survival) tse <- crohn_survival # Test with original counts - fit_counts <- getSurvival( + fit_counts <- getCox( tse, assay.type = "counts", time.col = "event_time", @@ -286,7 +286,7 @@ test_that("getSurvival handles different assay types", { # Transform and test with relative abundances tse <- transformAssay(tse, method = "relabundance") - fit_relabundance <- getSurvival( + fit_relabundance <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -303,7 +303,7 @@ test_that("getSurvival handles different assay types", { # Add CLR transformation and test tse <- transformAssay(tse, method = "clr", pseudocount = TRUE) - fit_clr <- getSurvival( + fit_clr <- getCox( tse, assay.type = "clr", time.col = "event_time", @@ -315,7 +315,7 @@ test_that("getSurvival handles different assay types", { }) # Check that methods results are reproducible -test_that("getSurvival results are reproducible", { +test_that("getCox results are reproducible", { # Load and prepare data data(crohn_survival) tse <- crohn_survival @@ -323,7 +323,7 @@ test_that("getSurvival results are reproducible", { # Set seed and run analysis set.seed(123) - fit1 <- getSurvival( + fit1 <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -333,7 +333,7 @@ test_that("getSurvival results are reproducible", { # Set same seed and run analysis again set.seed(123) - fit2 <- getSurvival( + fit2 <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -347,14 +347,14 @@ test_that("getSurvival results are reproducible", { expect_equal(fit1$c_index, fit2$c_index) }) # Check that the response is not used as a predictor -test_that("getSurvival does not use time or event as predictors", { +test_that("getCox does not use time or event as predictors", { data(crohn_survival) tse <- crohn_survival tse <- transformAssay(tse, method = "relabundance") tse <- tse[order(-rowMeans(assay(tse, "relabundance")))[1:5], ] colData(tse)[["age"]] <- seq_len(ncol(tse)) - fit <- getSurvival( + fit <- getCox( tse, assay.type = "relabundance", time.col = "event_time", @@ -368,31 +368,31 @@ test_that("getSurvival does not use time or event as predictors", { expect_setequal(names(fit$coef), c(rownames(tse), "age")) }) -# Check that addSurvival stores results in rowData, colData and metadata -test_that("addSurvival adds coefficients, risk scores and results", { +# Check that addCox stores results in rowData, colData and metadata +test_that("addCox adds coefficients, risk scores and results", { data(crohn_survival) tse <- crohn_survival tse <- transformAssay(tse, method = "relabundance") set.seed(1) - res <- getSurvival( + res <- getCox( tse, assay.type = "relabundance", time.col = "event_time", event.col = "event" ) set.seed(1) - tse <- addSurvival( + tse <- addCox( tse, assay.type = "relabundance", time.col = "event_time", event.col = "event" ) - coefs <- rowData(tse)[["survival_coef"]] + coefs <- rowData(tse)[["cox_coef"]] names(coefs) <- rownames(tse) expect_equal(coefs[names(res$coef)], res$coef) expect_true(all(is.na(coefs[!names(coefs) %in% names(res$coef)]))) - expect_equal(tse[["survival_risk_score"]], res$risk_scores) - expect_equal(metadata(tse)[["survival"]]$c_index, res$c_index) + expect_equal(tse[["cox_risk_score"]], res$risk_scores) + expect_equal(metadata(tse)[["cox"]]$c_index, res$c_index) }) From 02c4a65f17ad5abf6e291508db7ae4fe184c1f24 Mon Sep 17 00:00:00 2001 From: Muluh <127390183+0xMuluh@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:17:11 +0200 Subject: [PATCH 2/2] getCox: deprecate getSurvival and addSurvival, add a plot method --- DESCRIPTION | 2 +- NAMESPACE | 18 +++++++- NEWS | 4 +- R/deprecate.R | 66 ++++++++++++++++++++++++++ R/getCox.R | 90 ++++++++++++++++++++++++++++-------- _pkgdown.yml | 4 ++ man/deprecate.Rd | 46 ++++++++++++++++++ man/getCox.Rd | 42 ++++++++--------- tests/testthat/test-getCox.R | 50 ++++++++++++++++++++ 9 files changed, 277 insertions(+), 45 deletions(-) create mode 100644 R/deprecate.R create mode 100644 man/deprecate.Rd diff --git a/DESCRIPTION b/DESCRIPTION index b9357e2..a4487fd 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -27,6 +27,7 @@ Depends: mia Imports: dplyr, + ggplot2, glmnet, methods, S4Vectors, @@ -39,7 +40,6 @@ Imports: Suggests: BiocStyle, devtools, - ggplot2, knitr, lubridate, miaViz, diff --git a/NAMESPACE b/NAMESPACE index 56ba025..523f8f6 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,5 +1,6 @@ # Generated by roxygen2: do not edit by hand +S3method(plot,miatime_cox) export(addBaselineDivergence) export(addBimodality) export(addCox) @@ -7,6 +8,7 @@ export(addRankShift) export(addShortTermChange) export(addStability) export(addStepwiseDivergence) +export(addSurvival) export(getBaselineDivergence) export(getBimodality) export(getCox) @@ -15,6 +17,7 @@ export(getSamplingSummary) export(getShortTermChange) export(getStability) export(getStepwiseDivergence) +export(getSurvival) exportMethods(addBaselineDivergence) exportMethods(addBimodality) exportMethods(addCox) @@ -22,6 +25,7 @@ exportMethods(addRankShift) exportMethods(addShortTermChange) exportMethods(addStability) exportMethods(addStepwiseDivergence) +exportMethods(addSurvival) exportMethods(getBaselineDivergence) exportMethods(getBimodality) exportMethods(getCox) @@ -30,6 +34,7 @@ exportMethods(getSamplingSummary) exportMethods(getShortTermChange) exportMethods(getStability) exportMethods(getStepwiseDivergence) +exportMethods(getSurvival) import(S4Vectors) import(SingleCellExperiment) import(SummarizedExperiment) @@ -56,6 +61,16 @@ importFrom(dplyr, ungroup, vars ) +importFrom(ggplot2, + .data, + aes, + geom_point, + geom_segment, + geom_step, + ggplot, + labs, + theme_minimal +) importFrom(glmnet, Cindex, cv.glmnet, @@ -70,7 +85,8 @@ importFrom(stats, ) importFrom(survival, Surv, - coxph + coxph, + survfit ) importFrom(tidyr, pivot_wider, diff --git a/NEWS b/NEWS index ae8d3dd..3fc2cce 100755 --- a/NEWS +++ b/NEWS @@ -1,5 +1,7 @@ Changes in version 1.5.x -+ Renamed getSurvival and addSurvival to getCox and addCox, and nvar to max.features; added examples that summarise and plot the results ++ getCox and addCox replace getSurvival and addSurvival, which are deprecated; nvar is now max.features ++ getCox results have a plot() method for the coefficients and for the survival curves of high and low risk samples ++ getCox: max.features (nvar in getSurvival) failed with "incorrect number of dimensions" Changes in version 1.5.2 (2026-12-03) + Added getRankShift and addRankShift diff --git a/R/deprecate.R b/R/deprecate.R new file mode 100644 index 0000000..4806e97 --- /dev/null +++ b/R/deprecate.R @@ -0,0 +1,66 @@ +#' Deprecated functions +#' +#' These functions are deprecated. Use the functions named in the messages +#' instead. +#' +#' \code{getSurvival()} and \code{addSurvival()} are replaced by +#' \code{\link{getCox}()} and \code{\link{addCox}()}. Their argument +#' \code{nvar} is \code{max.features} in the new functions. +#' \code{addSurvival()} keeps its earlier default \code{name}. +#' +#' @param x A +#' \code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}} +#' object. +#' +#' @param name \code{Character vector} of length 3. Names for the results, as +#' in \code{\link{addCox}()}. +#' (Default: \code{c("survival_coef", "survival_risk_score", "survival")}) +#' +#' @param ... Additional arguments. See the replacing function. +#' +#' @return See the replacing function. +#' +#' @name deprecate +NULL + +#' @rdname deprecate +#' @export +setGeneric("getSurvival", signature = "x", function(x, ...) + standardGeneric("getSurvival")) + +#' @rdname deprecate +#' @export +setMethod("getSurvival", signature = c(x = "SummarizedExperiment"), + function(x, ...){ + .Deprecated(msg = paste0( + "'getSurvival' is deprecated. Use 'getCox' instead; ", + "'nvar' is now 'max.features'.")) + args <- c(list(x = x), .rename_nvar(list(...))) + do.call(getCox, args) + } +) + +#' @rdname deprecate +#' @export +setGeneric("addSurvival", signature = "x", function(x, ...) + standardGeneric("addSurvival")) + +#' @rdname deprecate +#' @export +setMethod("addSurvival", signature = c(x = "SummarizedExperiment"), + function( + x, name = c("survival_coef", "survival_risk_score", "survival"), + ...){ + .Deprecated(msg = paste0( + "'addSurvival' is deprecated. Use 'addCox' instead; ", + "'nvar' is now 'max.features'.")) + args <- c(list(x = x, name = name), .rename_nvar(list(...))) + do.call(addCox, args) + } +) + +# The argument 'nvar' of getSurvival() is 'max.features' in getCox() +.rename_nvar <- function(args){ + names(args)[names(args) == "nvar"] <- "max.features" + return(args) +} diff --git a/R/getCox.R b/R/getCox.R index 06417d8..f298ea1 100644 --- a/R/getCox.R +++ b/R/getCox.R @@ -41,6 +41,9 @@ #' for features not in the model), the risk scores to \code{colData}, and the #' full results to \code{metadata}. #' +#' @param x A \code{SummarizedExperiment} object. For \code{plot()}, the +#' result of \code{getCox()}. +#' #' @param time.col \code{Character scalar}. Column name in \code{colData(x)} #' representing time to event or follow-up time. Must be numeric. #' @@ -87,7 +90,13 @@ #' #' @inheritParams addBaselineDivergence #' -#' @return \code{getCox()} returns a list with model summaries: +#' @param type \code{Character scalar}. What \code{plot()} shows: +#' \code{"coef"} for the coefficients of the features in the model, or +#' \code{"survival"} for Kaplan-Meier curves of the samples with risk scores +#' above and below the median. (Default: \code{"coef"}) +#' +#' @return \code{getCox()} returns a list of class \code{"miatime_cox"} with +#' model summaries: #' \itemize{ #' \item \code{coef}: estimated model coefficients #' \item \code{risk_scores}: predicted risk scores @@ -95,8 +104,11 @@ #' \item \code{c_index_cv_mean}: mean cross-validated C-index (if penalized) #' \item \code{c_index_cv_sd}: SD of cross-validated C-index (if penalized) #' \item \code{fit}: fitted model object (coxph or cv.glmnet) +#' \item \code{time}, \code{event}: time to event and event status of the +#' samples #' } #' \code{addCox()} returns \code{x} with the results added. +#' \code{plot()} returns a \code{ggplot} object. #' #' @seealso \code{\link[coda4microbiome]{coda_coxnet}}, #' \code{\link[glmnet]{cv.glmnet}} @@ -117,28 +129,15 @@ #' time.col = "event_time", event.col = "event" #' ) #' -#' # Features in the model, by coefficient, and the concordance index -#' coefs <- rowData(tse)[["cox_coef"]] -#' names(coefs) <- rownames(tse) -#' coefs <- sort(coefs[!is.na(coefs) & coefs != 0]) -#' data.frame(feature = names(coefs), coefficient = unname(coefs)) -#' metadata(tse)[["cox"]][["c_index"]] -#' -#' # The coefficients -#' op <- par(mar = c(4, 14, 1, 1)) -#' barplot(coefs, horiz = TRUE, las = 1, xlab = "Coefficient") -#' par(op) +#' # The concordance index and the coefficients of the features in the model +#' res <- metadata(tse)[["cox"]] +#' res[["c_index"]] +#' plot(res) #' #' # Time to event of samples with risk scores above and below the median; #' # the scores come from the data the model was fitted to, so the separation #' # is optimistic -#' df <- data.frame(time = tse$event_time, event = tse$event, -#' risk = ifelse(tse$cox_risk_score > median(tse$cox_risk_score), -#' "high", "low")) -#' km <- survival::survfit(survival::Surv(time, event) ~ risk, data = df) -#' plot(km, col = c("red", "blue"), xlab = "Time", ylab = "Without event") -#' legend("bottomleft", legend = c("high risk", "low risk"), -#' col = c("red", "blue"), lty = 1) +#' plot(res, type = "survival") #' NULL @@ -181,10 +180,61 @@ setMethod("getCox", signature(x = "SummarizedExperiment"), args <- c(args, list(...)) # Fit survival model res <- do.call(.calc_survival, args) + # Keep the outcome for plotting + res[["time"]] <- args[["time"]] + res[["event"]] <- args[["status"]] + class(res) <- c("miatime_cox", class(res)) return(res) } ) +#' @rdname getCox +#' @importFrom ggplot2 ggplot aes .data geom_segment geom_point geom_step labs +#' theme_minimal +#' @importFrom survival Surv survfit +#' @importFrom stats median +#' @export +plot.miatime_cox <- function(x, type = c("coef", "survival"), ...){ + type <- match.arg(type) + if( type == "coef" ){ + coefs <- sort(x[["coef"]][x[["coef"]] != 0]) + if( length(coefs) == 0L ){ + stop("The model has no features with a nonzero coefficient.", + call. = FALSE) + } + df <- data.frame( + feature = factor(names(coefs), levels = names(coefs)), + coef = unname(coefs)) + p <- ggplot(df, aes(x = .data[["coef"]], y = .data[["feature"]])) + + geom_segment(aes(x = 0, xend = .data[["coef"]], + yend = .data[["feature"]])) + + geom_point() + + labs(x = "Coefficient", y = NULL) + + theme_minimal() + } else { + risk <- ifelse( + x[["risk_scores"]] > median(x[["risk_scores"]]), "high", "low") + if( length(unique(risk)) < 2L ){ + stop("The risk scores do not split the samples into two groups.", + call. = FALSE) + } + df <- data.frame(time = x[["time"]], event = x[["event"]], risk = risk) + km <- survfit(Surv(time, event) ~ risk, data = df) + # Each curve starts from all samples without the event at time 0 + groups <- sub("^risk=", "", names(km[["strata"]])) + df <- data.frame( + time = c(rep(0, length(groups)), km[["time"]]), + surv = c(rep(1, length(groups)), km[["surv"]]), + risk = c(groups, rep(groups, km[["strata"]]))) + p <- ggplot(df, aes(x = .data[["time"]], y = .data[["surv"]], + colour = .data[["risk"]])) + + geom_step() + + labs(x = "Time", y = "Without event", colour = "Risk") + + theme_minimal() + } + return(p) +} + ############################# Internal helpers ################################# # Check input validity for survival analysis @@ -415,7 +465,7 @@ setMethod("getCox", signature(x = "SummarizedExperiment"), # If such lambdas exist, choose the lambda for model that has # highest number of taxa. if( length(valid) > 0L ){ - lambda <- fit[["glmnet.fit"]][max(valid), "lambda"] + lambda <- fit[["glmnet.fit"]][["lambda"]][max(valid)] } } # Handle lambda selection by name diff --git a/_pkgdown.yml b/_pkgdown.yml index 8be2f8f..9a32221 100755 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -35,3 +35,7 @@ reference: - title: Package contents: - miaTime-package + +- title: Deprecated + contents: + - deprecate diff --git a/man/deprecate.Rd b/man/deprecate.Rd new file mode 100644 index 0000000..dd2bc8f --- /dev/null +++ b/man/deprecate.Rd @@ -0,0 +1,46 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/deprecate.R +\name{deprecate} +\alias{deprecate} +\alias{getSurvival} +\alias{getSurvival,SummarizedExperiment-method} +\alias{addSurvival} +\alias{addSurvival,SummarizedExperiment-method} +\title{Deprecated functions} +\usage{ +getSurvival(x, ...) + +\S4method{getSurvival}{SummarizedExperiment}(x, ...) + +addSurvival(x, ...) + +\S4method{addSurvival}{SummarizedExperiment}( + x, + name = c("survival_coef", "survival_risk_score", "survival"), + ... +) +} +\arguments{ +\item{x}{A +\code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}} +object.} + +\item{...}{Additional arguments. See the replacing function.} + +\item{name}{\code{Character vector} of length 3. Names for the results, as +in \code{\link{addCox}()}. +(Default: \code{c("survival_coef", "survival_risk_score", "survival")})} +} +\value{ +See the replacing function. +} +\description{ +These functions are deprecated. Use the functions named in the messages +instead. +} +\details{ +\code{getSurvival()} and \code{addSurvival()} are replaced by +\code{\link{getCox}()} and \code{\link{addCox}()}. Their argument +\code{nvar} is \code{max.features} in the new functions. +\code{addSurvival()} keeps its earlier default \code{name}. +} diff --git a/man/getCox.Rd b/man/getCox.Rd index 7421249..d56b6af 100644 --- a/man/getCox.Rd +++ b/man/getCox.Rd @@ -5,6 +5,7 @@ \alias{addCox} \alias{addCox,SummarizedExperiment-method} \alias{getCox,SummarizedExperiment-method} +\alias{plot.miatime_cox} \title{Survival analysis} \usage{ getCox(x, ...) @@ -20,11 +21,12 @@ addCox(x, ...) ) \S4method{getCox}{SummarizedExperiment}(x, time.col, event.col, assay.type = "counts", col.var = NULL, ...) + +\method{plot}{miatime_cox}(x, type = c("coef", "survival"), ...) } \arguments{ -\item{x}{A -\code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}} -object.} +\item{x}{A \code{SummarizedExperiment} object. For \code{plot()}, the +result of \code{getCox()}.} \item{...}{additional arguments. \itemize{ @@ -72,9 +74,15 @@ used in the dissimilarity estimation. (Default: \code{"counts"})} \item{col.var}{\code{Character vector}. Optional. Specifies covariate columns in \code{colData(x)} to adjust for in the survival model. (Default: \code{NULL})} + +\item{type}{\code{Character scalar}. What \code{plot()} shows: +\code{"coef"} for the coefficients of the features in the model, or +\code{"survival"} for Kaplan-Meier curves of the samples with risk scores +above and below the median. (Default: \code{"coef"})} } \value{ -\code{getCox()} returns a list with model summaries: +\code{getCox()} returns a list of class \code{"miatime_cox"} with +model summaries: \itemize{ \item \code{coef}: estimated model coefficients \item \code{risk_scores}: predicted risk scores @@ -82,8 +90,11 @@ columns in \code{colData(x)} to adjust for in the survival model. \item \code{c_index_cv_mean}: mean cross-validated C-index (if penalized) \item \code{c_index_cv_sd}: SD of cross-validated C-index (if penalized) \item \code{fit}: fitted model object (coxph or cv.glmnet) +\item \code{time}, \code{event}: time to event and event status of the +samples } \code{addCox()} returns \code{x} with the results added. +\code{plot()} returns a \code{ggplot} object. } \description{ Fit a (penalized) Cox proportional hazards model on microbiome data contained @@ -130,28 +141,15 @@ tse <- addCox( time.col = "event_time", event.col = "event" ) -# Features in the model, by coefficient, and the concordance index -coefs <- rowData(tse)[["cox_coef"]] -names(coefs) <- rownames(tse) -coefs <- sort(coefs[!is.na(coefs) & coefs != 0]) -data.frame(feature = names(coefs), coefficient = unname(coefs)) -metadata(tse)[["cox"]][["c_index"]] - -# The coefficients -op <- par(mar = c(4, 14, 1, 1)) -barplot(coefs, horiz = TRUE, las = 1, xlab = "Coefficient") -par(op) +# The concordance index and the coefficients of the features in the model +res <- metadata(tse)[["cox"]] +res[["c_index"]] +plot(res) # Time to event of samples with risk scores above and below the median; # the scores come from the data the model was fitted to, so the separation # is optimistic -df <- data.frame(time = tse$event_time, event = tse$event, - risk = ifelse(tse$cox_risk_score > median(tse$cox_risk_score), - "high", "low")) -km <- survival::survfit(survival::Surv(time, event) ~ risk, data = df) -plot(km, col = c("red", "blue"), xlab = "Time", ylab = "Without event") -legend("bottomleft", legend = c("high risk", "low risk"), - col = c("red", "blue"), lty = 1) +plot(res, type = "survival") } \references{ diff --git a/tests/testthat/test-getCox.R b/tests/testthat/test-getCox.R index 3841958..ae592b1 100644 --- a/tests/testthat/test-getCox.R +++ b/tests/testthat/test-getCox.R @@ -396,3 +396,53 @@ test_that("addCox adds coefficients, risk scores and results", { expect_equal(tse[["cox_risk_score"]], res$risk_scores) expect_equal(metadata(tse)[["cox"]]$c_index, res$c_index) }) + +test_that("getSurvival and addSurvival are deprecated wrappers", { + data(crohn_survival) + tse <- transformAssay(crohn_survival, method = "relabundance") + + set.seed(1) + res <- getCox( + tse, assay.type = "relabundance", + time.col = "event_time", event.col = "event", max.features = 3) + set.seed(1) + expect_warning( + res_old <- getSurvival( + tse, assay.type = "relabundance", + time.col = "event_time", event.col = "event", nvar = 3), + "deprecated") + expect_equal(res_old$coef, res$coef) + + set.seed(1) + expect_warning( + tse_old <- addSurvival( + tse, assay.type = "relabundance", + time.col = "event_time", event.col = "event", nvar = 3), + "deprecated") + expect_equal(tse_old[["survival_risk_score"]], res$risk_scores) + expect_equal(metadata(tse_old)[["survival"]]$coef, res$coef) +}) + +test_that("plot shows the coefficients and the survival curves", { + data(crohn_survival) + tse <- transformAssay(crohn_survival, method = "relabundance") + set.seed(1) + res <- getCox( + tse, assay.type = "relabundance", + time.col = "event_time", event.col = "event") + + expect_s3_class(res, "miatime_cox") + expect_equal(res$time, tse$event_time) + expect_equal(res$event, as.numeric(tse$event)) + + p <- plot(res) + expect_s3_class(p, "ggplot") + expect_setequal(as.character(p$data$feature), names(res$coef)) + + p <- plot(res, type = "survival") + expect_s3_class(p, "ggplot") + expect_setequal(unique(p$data$risk), c("high", "low")) + expect_true(all(p$data$surv >= 0 & p$data$surv <= 1)) + + expect_error(plot(res, type = "wrong")) +})