From 648d93739d29c816193e50187552121d49607d95 Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Thu, 12 Nov 2026 14:02:29 -0800 Subject: [PATCH 01/10] Compare strategies with a user-selected reference in calculate_icers() calculate_icers() gains ref_str, wtp, nhb, and currency (added after the existing arguments, so positional calls keep working). The frontier (Status, Inc_Cost, Inc_Effect, ICER) is computed exactly as before and is never changed; the new columns are added afterwards by add_reference_and_nmb(), and only for the arguments that are given, so with the defaults the object is identical to before. - ref_str: Inc_Cost_ref, Inc_Effect_ref, ICER_ref (numeric, NA where a ratio is not meaningful), and Status_ref ('Reference', 'Dominant', 'Dominated', 'More costly, more effective', 'Less costly, less effective', or 'Equivalent' for the same cost and effect) (#209). - wtp: NMB, plus iNMB_ref with a reference (#200); nhb = TRUE also adds NHB and iNHB_ref. - currency: stored on the object and used by print.icers(). - print.icers() gains ref = c('sequential', 'reference', 'both'); the default prints the same table as before. Headers name the reference ('Incremental Costs vs Standard of care ($)'). - Validation helpers check_ref_str() and check_wtp_nhb() with clear errors; a new example in ?calculate_icers. Tests (test_icers_reference.R) check hand-calculated values for every Status_ref category, a dominated and a most-expensive reference, hund_strat, NMB/NHB, one and two strategies, names with spaces, the errors, and the print views. The default printed tables are identical to main's print.icers(). Part of #209. Closes #200 --- NEWS.md | 3 + R/icers.R | 211 +++++++++++++++++++++++--- man/add_reference_and_nmb.Rd | 33 ++++ man/calculate_icers.Rd | 48 +++++- man/check_ref_str.Rd | 20 +++ man/check_wtp_nhb.Rd | 22 +++ man/print.icers.Rd | 21 ++- man/status_vs_reference.Rd | 18 +++ tests/testthat/test_icers_reference.R | 123 +++++++++++++++ 9 files changed, 470 insertions(+), 29 deletions(-) create mode 100644 man/add_reference_and_nmb.Rd create mode 100644 man/check_ref_str.Rd create mode 100644 man/check_wtp_nhb.Rd create mode 100644 man/status_vs_reference.Rd create mode 100644 tests/testthat/test_icers_reference.R diff --git a/NEWS.md b/NEWS.md index cea9f3c..8878a02 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,9 @@ ## New features +- `calculate_icers()` can compare every strategy with a user-selected reference strategy: with `ref_str = "Standard of care"`, it adds `Inc_Cost_ref`, `Inc_Effect_ref`, `ICER_ref`, and `Status_ref` ("Reference", "Dominant", "Dominated", "More costly, more effective", "Less costly, less effective", or "Equivalent"). The frontier-based results are unchanged, and without `ref_str` no columns are added (#209). +- `calculate_icers()` gains `wtp`, which adds the net monetary benefit (`NMB`, and `iNMB_ref` with a reference strategy), and `nhb = TRUE`, which also adds the net health benefit (`NHB`, `iNHB_ref`) (#200). +- `calculate_icers()` gains `currency`, used by `print.icers()`. `print.icers()` gains `ref`: `"sequential"` (the default) prints the usual table, and `"reference"` or `"both"` print the comparison with the reference strategy (#209). - `print.icers()` prints a formatted ICER table, with options for the currency symbol and the number of digits (#184, #171). - `plot.psa()` gains a `ref_str` argument that plots the PSA on the incremental cost-effectiveness plane relative to a chosen reference strategy (#188). - Plotting functions now default to an accessible, colorblind-friendly palette (`col = "access"`, based on viridis). The previous palettes remain available as `col = "full"` and `col = "bw"`. diff --git a/R/icers.R b/R/icers.R index f5dc898..266bb4d 100644 --- a/R/icers.R +++ b/R/icers.R @@ -14,9 +14,33 @@ #' @param cost vector of cost for each strategy #' @param effect vector of effect for each strategy #' @param strategies string vector of strategy names +#' @param ref_str name of a reference strategy (one of \code{strategies}) to compare every +#' strategy against, for example \code{"Standard of care"}. The default (\code{NULL}) adds no +#' reference columns. The frontier-based results (\code{Status}, \code{Inc_Cost}, +#' \code{Inc_Effect}, \code{ICER}) never depend on the reference. +#' @param wtp a single willingness-to-pay threshold (currency per unit of effect). If given, +#' the net monetary benefit (\code{NMB}) of each strategy is added. The default (\code{NULL}) +#' adds no net-benefit columns. +#' @param nhb if \code{TRUE}, also add the net health benefit (\code{NHB}). Requires \code{wtp}. +#' @param currency currency symbol used when printing and plotting the results, for example +#' \code{"€"}. The default (\code{NULL}) uses \code{"$"}. #' #' @return A data frame and \code{icers} object of strategies and their associated -#' status, incremental cost, incremental effect, and ICER. +#' status, incremental cost, incremental effect, and ICER, computed sequentially along the +#' cost-effectiveness frontier. +#' +#' If \code{ref_str} is given, four columns compare each strategy with the reference: +#' \code{Inc_Cost_ref} and \code{Inc_Effect_ref} (cost and effect minus those of the +#' reference), \code{ICER_ref}, and \code{Status_ref}, one of \code{"Reference"}, +#' \code{"Dominant"} (less costly and at least as effective), \code{"Dominated"} (more costly +#' and no more effective), \code{"More costly, more effective"}, +#' \code{"Less costly, less effective"}, or \code{"Equivalent"} (same cost and effect). +#' \code{ICER_ref} is \code{NA} where a ratio is not meaningful: for the reference itself and +#' for dominant, dominated, and equivalent strategies. +#' +#' If \code{wtp} is given, \code{NMB} (\code{wtp * Effect - Cost}) is added, and with +#' \code{ref_str} also \code{iNMB_ref}, the NMB minus that of the reference. With +#' \code{nhb = TRUE}, \code{NHB} (\code{Effect - Cost / wtp}) and \code{iNHB_ref} are added too. #' #' @seealso \code{\link{plot.icers}} #' @@ -52,8 +76,17 @@ #' # if using a small number of strategies, you can label all the points #' # note that longer strategy names will get truncated #' plot(icers, label = "all") +#' +#' ## Comparing every strategy with a reference strategy +#' hund_ref <- calculate_icers(hund_strat$Cost, +#' hund_strat$QALYs, +#' hund_strat$Strategy, +#' ref_str = hund_strat$Strategy[1], +#' wtp = 50000) +#' print(hund_ref, ref = "reference") #' @export -calculate_icers <- function(cost, effect, strategies) { +calculate_icers <- function(cost, effect, strategies, ref_str = NULL, wtp = NULL, + nhb = FALSE, currency = NULL) { # checks on input n_cost <- length(cost) n_eff <- length(effect) @@ -64,6 +97,8 @@ calculate_icers <- function(cost, effect, strategies) { if (n_strat == 0) { stop("cost, effect, and strategies must contain at least one strategy", call. = FALSE) } + ref_str <- check_ref_str(ref_str, as.character(strategies)) + check_wtp_nhb(wtp, nhb) Cost <- Effect <- Status <- Strategy <- Inc_Cost <- Inc_Effect <- ICER <- NULL @@ -85,7 +120,7 @@ calculate_icers <- function(cost, effect, strategies) { df_cea$ICER <- NA_real_ df_cea$Status <- "ND" class(df_cea) <- c("icers", "data.frame") - return(df_cea) + return(add_reference_and_nmb(df_cea, ref_str, wtp, nhb, currency)) } # three statuses: dominated, extended dominated, and non-dominated @@ -174,7 +209,105 @@ calculate_icers <- function(cost, effect, strategies) { # declare class of results class(df_results) <- c("icers", "data.frame") - df_results + add_reference_and_nmb(df_results, ref_str, wtp, nhb, currency) +} + +#' Check a reference strategy name +#' +#' @param ref_str reference strategy name, or \code{NULL}. +#' @param strategies names of the strategies in the analysis. +#' @return \code{ref_str} as a character string, or \code{NULL}. +#' @keywords internal +check_ref_str <- function(ref_str, strategies) { + if (is.null(ref_str)) { + return(NULL) + } + if (length(ref_str) != 1 || is.na(ref_str)) { + stop("`ref_str` must be a single strategy name.", call. = FALSE) + } + ref_str <- as.character(ref_str) + if (!ref_str %in% strategies) { + stop("`ref_str` must be one of the strategies: ", + paste0("\"", strategies, "\"", collapse = ", "), ".", call. = FALSE) + } + ref_str +} + +#' Check the willingness-to-pay and NHB arguments of calculate_icers() +#' +#' @inheritParams calculate_icers +#' @return \code{NULL}, invisibly; called for its errors. +#' @keywords internal +check_wtp_nhb <- function(wtp, nhb) { + if (!is.null(wtp) && (!is.numeric(wtp) || length(wtp) != 1 || !is.finite(wtp) || wtp < 0)) { + stop("`wtp` must be a single non-negative number.", call. = FALSE) + } + if (!isTRUE(nhb) && !isFALSE(nhb)) { + stop("`nhb` must be TRUE or FALSE.", call. = FALSE) + } + if (nhb && (is.null(wtp) || wtp == 0)) { + stop("`nhb = TRUE` requires `wtp` greater than zero.", call. = FALSE) + } + invisible(NULL) +} + +#' Status of each strategy relative to a reference strategy +#' +#' @param v_inc_cost,v_inc_effect cost and effect of each strategy minus those of the reference. +#' @return character vector of statuses (the reference itself is labeled by the caller). +#' @keywords internal +status_vs_reference <- function(v_inc_cost, v_inc_effect) { + ifelse(v_inc_cost == 0 & v_inc_effect == 0, "Equivalent", + ifelse(v_inc_cost <= 0 & v_inc_effect >= 0, "Dominant", + ifelse(v_inc_cost >= 0 & v_inc_effect <= 0, "Dominated", + ifelse(v_inc_cost > 0, "More costly, more effective", + "Less costly, less effective")))) +} + +#' Add reference-strategy and net-benefit columns to an icers object +#' +#' The frontier-based columns are not modified. Columns and attributes are only added +#' for the arguments that are given, so with all of them \code{NULL} the object is unchanged. +#' +#' @param df_icers an \code{icers} object. +#' @inheritParams calculate_icers +#' @return \code{df_icers} with the requested columns and attributes added. +#' @keywords internal +add_reference_and_nmb <- function(df_icers, ref_str, wtp, nhb, currency) { + if (!is.null(ref_str)) { + i_ref <- match(ref_str, df_icers$Strategy) + v_inc_cost <- df_icers$Cost - df_icers$Cost[i_ref] + v_inc_effect <- df_icers$Effect - df_icers$Effect[i_ref] + v_status <- status_vs_reference(v_inc_cost, v_inc_effect) + v_status[i_ref] <- "Reference" + v_inc_cost[i_ref] <- NA_real_ + v_inc_effect[i_ref] <- NA_real_ + v_has_ratio <- v_status %in% c("More costly, more effective", "Less costly, less effective") + df_icers$Inc_Cost_ref <- v_inc_cost + df_icers$Inc_Effect_ref <- v_inc_effect + df_icers$ICER_ref <- ifelse(v_has_ratio, v_inc_cost / v_inc_effect, NA_real_) + df_icers$Status_ref <- v_status + attr(df_icers, "ref_str") <- ref_str + } + if (!is.null(wtp)) { + df_icers$NMB <- wtp * df_icers$Effect - df_icers$Cost + if (!is.null(ref_str)) { + df_icers$iNMB_ref <- df_icers$NMB - df_icers$NMB[i_ref] + df_icers$iNMB_ref[i_ref] <- NA_real_ + } + if (nhb) { + df_icers$NHB <- df_icers$Effect - df_icers$Cost / wtp + if (!is.null(ref_str)) { + df_icers$iNHB_ref <- df_icers$NHB - df_icers$NHB[i_ref] + df_icers$iNHB_ref[i_ref] <- NA_real_ + } + } + attr(df_icers, "wtp") <- wtp + } + if (!is.null(currency)) { + attr(df_icers, "currency") <- currency + } + df_icers } #' Calculate incremental cost-effectiveness ratios from a \code{psa} object. @@ -406,24 +539,42 @@ plot.icers <- function(x, #' Print the formatted CEA table #' +#' By default, prints the sequential cost-effectiveness table: each strategy on the frontier is +#' compared with the previous one. If the \code{icers} object was created with a reference +#' strategy (\code{ref_str} in \code{\link{calculate_icers}}), \code{ref = "reference"} shows the +#' comparison of every strategy with the reference instead, and \code{ref = "both"} shows both. +#' #' @param x Object of class \code{icers} #' @param currency string. with currency used in the cost-effectiveness analysis (CEA). +#' Defaults to the currency stored in \code{x}, or \code{"$"}. #' @param dig_cost integer. number of digits to round costs to #' @param dig_eff integer. number of digits to round effects to #' @param dig_icer integer. number of digits to round ICER to +#' @param ref which comparison to show: \code{"sequential"} (the default), \code{"reference"}, +#' or \code{"both"}. #' @param ... Additional arguments passed to other methods. #' @return a dataframe object - formatted CEA table #' @export print.icers <- function(x, - currency = "$", + currency = NULL, dig_cost = 0, dig_eff = 2, dig_icer = 0, + ref = c("sequential", "reference", "both"), ...) { # check if icers object if (!inherits(x, "icers")) { stop("x must be an object of class icers") } + ref <- match.arg(ref) + if (is.null(currency)) { + currency <- if (is.null(attr(x, "currency"))) "$" else attr(x, "currency") + } + ref_str <- attr(x, "ref_str") + if (ref != "sequential" && is.null(ref_str)) { + stop("x has no reference strategy; create it with calculate_icers(..., ref_str = ) ", + "to use ref = \"", ref, "\".", call. = FALSE) + } format_numbers <- function(col, n_digits) { v_new_col <- rep("-", length(col)) @@ -439,26 +590,38 @@ print.icers <- function(x, v_new_col } - df_table_cea <- x - df_table_cea$Cost <- format_numbers(df_table_cea$Cost, n_digits = dig_cost) - df_table_cea$Inc_Cost <- format_numbers(df_table_cea$Inc_Cost, n_digits = dig_cost) - df_table_cea$Effect <- format_numbers(df_table_cea$Effect, n_digits = dig_eff) - df_table_cea$Inc_Effect <- format_numbers(df_table_cea$Inc_Effect, n_digits = dig_eff) - df_table_cea$ICER <- format_numbers(df_table_cea$ICER, n_digits = dig_icer) - - colnames(df_table_cea)[colnames(df_table_cea) - %in% c("Cost", - "Effect", - "Inc_Cost", - "Inc_Effect", - "ICER")] <- - c(paste0("Costs (", currency, ")"), - "QALYs", - paste0("Incremental Costs (", currency, ")"), - "Incremental QALYs", - paste0("ICER (", currency, "/QALY)")) - + # columns that belong to each view + v_seq_cols <- c("Inc_Cost", "Inc_Effect", "ICER", "Status") + v_ref_cols <- c("Inc_Cost_ref", "Inc_Effect_ref", "ICER_ref", "Status_ref", "iNMB_ref", "iNHB_ref") + v_drop <- switch(ref, sequential = v_ref_cols, reference = v_seq_cols, both = character(0)) + df_table_cea <- x class(df_table_cea) <- "data.frame" + df_table_cea <- df_table_cea[, setdiff(names(df_table_cea), v_drop), drop = FALSE] + + # display digits and header for each known column + vs <- paste0(" vs ", ref_str) + l_format <- list( + Cost = list(dig_cost, paste0("Costs (", currency, ")")), + Effect = list(dig_eff, "QALYs"), + Inc_Cost = list(dig_cost, paste0("Incremental Costs (", currency, ")")), + Inc_Effect = list(dig_eff, "Incremental QALYs"), + ICER = list(dig_icer, paste0("ICER (", currency, "/QALY)")), + Inc_Cost_ref = list(dig_cost, paste0("Incremental Costs", vs, " (", currency, ")")), + Inc_Effect_ref = list(dig_eff, paste0("Incremental QALYs", vs)), + ICER_ref = list(dig_icer, paste0("ICER", vs, " (", currency, "/QALY)")), + Status_ref = list(NA, paste0("Status", vs)), + NMB = list(dig_cost, paste0("NMB (", currency, ")")), + iNMB_ref = list(dig_cost, paste0("iNMB", vs, " (", currency, ")")), + NHB = list(dig_eff, "NHB (QALYs)"), + iNHB_ref = list(dig_eff, paste0("iNHB", vs, " (QALYs)")) + ) + for (col in intersect(names(l_format), names(df_table_cea))) { + if (!is.na(l_format[[col]][[1]])) { + df_table_cea[[col]] <- format_numbers(df_table_cea[[col]], n_digits = l_format[[col]][[1]]) + } + names(df_table_cea)[names(df_table_cea) == col] <- l_format[[col]][[2]] + } + print(df_table_cea) invisible(df_table_cea) } diff --git a/man/add_reference_and_nmb.Rd b/man/add_reference_and_nmb.Rd new file mode 100644 index 0000000..7d4f97b --- /dev/null +++ b/man/add_reference_and_nmb.Rd @@ -0,0 +1,33 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/icers.R +\name{add_reference_and_nmb} +\alias{add_reference_and_nmb} +\title{Add reference-strategy and net-benefit columns to an icers object} +\usage{ +add_reference_and_nmb(df_icers, ref_str, wtp, nhb, currency) +} +\arguments{ +\item{df_icers}{an \code{icers} object.} + +\item{ref_str}{name of a reference strategy (one of \code{strategies}) to compare every +strategy against, for example \code{"Standard of care"}. The default (\code{NULL}) adds no +reference columns. The frontier-based results (\code{Status}, \code{Inc_Cost}, +\code{Inc_Effect}, \code{ICER}) never depend on the reference.} + +\item{wtp}{a single willingness-to-pay threshold (currency per unit of effect). If given, +the net monetary benefit (\code{NMB}) of each strategy is added. The default (\code{NULL}) +adds no net-benefit columns.} + +\item{nhb}{if \code{TRUE}, also add the net health benefit (\code{NHB}). Requires \code{wtp}.} + +\item{currency}{currency symbol used when printing and plotting the results, for example +\code{"€"}. The default (\code{NULL}) uses \code{"$"}.} +} +\value{ +\code{df_icers} with the requested columns and attributes added. +} +\description{ +The frontier-based columns are not modified. Columns and attributes are only added +for the arguments that are given, so with all of them \code{NULL} the object is unchanged. +} +\keyword{internal} diff --git a/man/calculate_icers.Rd b/man/calculate_icers.Rd index 35b54da..0c4132b 100644 --- a/man/calculate_icers.Rd +++ b/man/calculate_icers.Rd @@ -4,7 +4,15 @@ \alias{calculate_icers} \title{Calculate incremental cost-effectiveness ratios (ICERs)} \usage{ -calculate_icers(cost, effect, strategies) +calculate_icers( + cost, + effect, + strategies, + ref_str = NULL, + wtp = NULL, + nhb = FALSE, + currency = NULL +) } \arguments{ \item{cost}{vector of cost for each strategy} @@ -12,10 +20,38 @@ calculate_icers(cost, effect, strategies) \item{effect}{vector of effect for each strategy} \item{strategies}{string vector of strategy names} + +\item{ref_str}{name of a reference strategy (one of \code{strategies}) to compare every +strategy against, for example \code{"Standard of care"}. The default (\code{NULL}) adds no +reference columns. The frontier-based results (\code{Status}, \code{Inc_Cost}, +\code{Inc_Effect}, \code{ICER}) never depend on the reference.} + +\item{wtp}{a single willingness-to-pay threshold (currency per unit of effect). If given, +the net monetary benefit (\code{NMB}) of each strategy is added. The default (\code{NULL}) +adds no net-benefit columns.} + +\item{nhb}{if \code{TRUE}, also add the net health benefit (\code{NHB}). Requires \code{wtp}.} + +\item{currency}{currency symbol used when printing and plotting the results, for example +\code{"€"}. The default (\code{NULL}) uses \code{"$"}.} } \value{ A data frame and \code{icers} object of strategies and their associated -status, incremental cost, incremental effect, and ICER. +status, incremental cost, incremental effect, and ICER, computed sequentially along the +cost-effectiveness frontier. + +If \code{ref_str} is given, four columns compare each strategy with the reference: +\code{Inc_Cost_ref} and \code{Inc_Effect_ref} (cost and effect minus those of the +reference), \code{ICER_ref}, and \code{Status_ref}, one of \code{"Reference"}, +\code{"Dominant"} (less costly and at least as effective), \code{"Dominated"} (more costly +and no more effective), \code{"More costly, more effective"}, +\code{"Less costly, less effective"}, or \code{"Equivalent"} (same cost and effect). +\code{ICER_ref} is \code{NA} where a ratio is not meaningful: for the reference itself and +for dominant, dominated, and equivalent strategies. + +If \code{wtp} is given, \code{NMB} (\code{wtp * Effect - Cost}) is added, and with +\code{ref_str} also \code{iNMB_ref}, the NMB minus that of the reference. With +\code{nhb = TRUE}, \code{NHB} (\code{Effect - Cost / wtp}) and \code{iNHB_ref} are added too. } \description{ This function takes in strategies and their associated cost and effect, assigns them @@ -60,6 +96,14 @@ plot(icers) # if using a small number of strategies, you can label all the points # note that longer strategy names will get truncated plot(icers, label = "all") + +## Comparing every strategy with a reference strategy +hund_ref <- calculate_icers(hund_strat$Cost, + hund_strat$QALYs, + hund_strat$Strategy, + ref_str = hund_strat$Strategy[1], + wtp = 50000) +print(hund_ref, ref = "reference") } \seealso{ \code{\link{plot.icers}} diff --git a/man/check_ref_str.Rd b/man/check_ref_str.Rd new file mode 100644 index 0000000..38e818a --- /dev/null +++ b/man/check_ref_str.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/icers.R +\name{check_ref_str} +\alias{check_ref_str} +\title{Check a reference strategy name} +\usage{ +check_ref_str(ref_str, strategies) +} +\arguments{ +\item{ref_str}{reference strategy name, or \code{NULL}.} + +\item{strategies}{names of the strategies in the analysis.} +} +\value{ +\code{ref_str} as a character string, or \code{NULL}. +} +\description{ +Check a reference strategy name +} +\keyword{internal} diff --git a/man/check_wtp_nhb.Rd b/man/check_wtp_nhb.Rd new file mode 100644 index 0000000..93039de --- /dev/null +++ b/man/check_wtp_nhb.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/icers.R +\name{check_wtp_nhb} +\alias{check_wtp_nhb} +\title{Check the willingness-to-pay and NHB arguments of calculate_icers()} +\usage{ +check_wtp_nhb(wtp, nhb) +} +\arguments{ +\item{wtp}{a single willingness-to-pay threshold (currency per unit of effect). If given, +the net monetary benefit (\code{NMB}) of each strategy is added. The default (\code{NULL}) +adds no net-benefit columns.} + +\item{nhb}{if \code{TRUE}, also add the net health benefit (\code{NHB}). Requires \code{wtp}.} +} +\value{ +\code{NULL}, invisibly; called for its errors. +} +\description{ +Check the willingness-to-pay and NHB arguments of calculate_icers() +} +\keyword{internal} diff --git a/man/print.icers.Rd b/man/print.icers.Rd index a010fc5..8467e45 100644 --- a/man/print.icers.Rd +++ b/man/print.icers.Rd @@ -4,12 +4,21 @@ \alias{print.icers} \title{Print the formatted CEA table} \usage{ -\method{print}{icers}(x, currency = "$", dig_cost = 0, dig_eff = 2, dig_icer = 0, ...) +\method{print}{icers}( + x, + currency = NULL, + dig_cost = 0, + dig_eff = 2, + dig_icer = 0, + ref = c("sequential", "reference", "both"), + ... +) } \arguments{ \item{x}{Object of class \code{icers}} -\item{currency}{string. with currency used in the cost-effectiveness analysis (CEA).} +\item{currency}{string. with currency used in the cost-effectiveness analysis (CEA). +Defaults to the currency stored in \code{x}, or \code{"$"}.} \item{dig_cost}{integer. number of digits to round costs to} @@ -17,11 +26,17 @@ \item{dig_icer}{integer. number of digits to round ICER to} +\item{ref}{which comparison to show: \code{"sequential"} (the default), \code{"reference"}, +or \code{"both"}.} + \item{...}{Additional arguments passed to other methods.} } \value{ a dataframe object - formatted CEA table } \description{ -Print the formatted CEA table +By default, prints the sequential cost-effectiveness table: each strategy on the frontier is +compared with the previous one. If the \code{icers} object was created with a reference +strategy (\code{ref_str} in \code{\link{calculate_icers}}), \code{ref = "reference"} shows the +comparison of every strategy with the reference instead, and \code{ref = "both"} shows both. } diff --git a/man/status_vs_reference.Rd b/man/status_vs_reference.Rd new file mode 100644 index 0000000..10def36 --- /dev/null +++ b/man/status_vs_reference.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/icers.R +\name{status_vs_reference} +\alias{status_vs_reference} +\title{Status of each strategy relative to a reference strategy} +\usage{ +status_vs_reference(v_inc_cost, v_inc_effect) +} +\arguments{ +\item{v_inc_cost, v_inc_effect}{cost and effect of each strategy minus those of the reference.} +} +\value{ +character vector of statuses (the reference itself is labeled by the caller). +} +\description{ +Status of each strategy relative to a reference strategy +} +\keyword{internal} diff --git a/tests/testthat/test_icers_reference.R b/tests/testthat/test_icers_reference.R new file mode 100644 index 0000000..0d410dc --- /dev/null +++ b/tests/testthat/test_icers_reference.R @@ -0,0 +1,123 @@ +context("calculate_icers() against a reference strategy (#209) and net benefit (#200)") + +# Toy example with one strategy in each position relative to the reference "Ref": +# strategy cost effect vs Ref: inc cost inc effect status +# Ref 100 1.0 - - Reference +# More 200 2.0 100 1.0 More costly, more effective (ICER 100) +# Cheaper 50 1.5 -50 0.5 Dominant +# Worse 300 0.5 200 -0.5 Dominated +# Less 80 0.8 -20 -0.2 Less costly, less effective (ICER 100) +# Same 100 1.0 0 0.0 Equivalent +df_toy <- data.frame(strategy = c("Ref", "More", "Cheaper", "Worse", "Less", "Same"), + cost = c(100, 200, 50, 300, 80, 100), + effect = c(1, 2, 1.5, 0.5, 0.8, 1), + stringsAsFactors = FALSE) +toy_icers <- function(...) { + calculate_icers(df_toy$cost, df_toy$effect, df_toy$strategy, ...) +} +row_of <- function(x, s) x[x$Strategy == s, ] + +test_that("without ref_str or wtp the output is unchanged", { + x <- toy_icers() + expect_identical(names(x), c("Strategy", "Cost", "Effect", "Inc_Cost", "Inc_Effect", "ICER", "Status")) + expect_null(attr(x, "ref_str")) +}) + +test_that("reference columns match hand calculations", { + x <- toy_icers(ref_str = "Ref") + # sequential (frontier) results are unchanged by ref_str + x0 <- toy_icers() + expect_equal(as.data.frame(x)[, names(x0)], as.data.frame(x0)) + expect_identical(attr(x, "ref_str"), "Ref") + + expected <- list( + Ref = list(NA_real_, NA_real_, NA_real_, "Reference"), + More = list(100, 1, 100, "More costly, more effective"), + Cheaper = list(-50, 0.5, NA_real_, "Dominant"), + Worse = list(200, -0.5, NA_real_, "Dominated"), + Less = list(-20, -0.2, 100, "Less costly, less effective"), + Same = list(0, 0, NA_real_, "Equivalent") + ) + for (s in names(expected)) { + r <- row_of(x, s) + expect_equal(r$Inc_Cost_ref, expected[[s]][[1]], info = s) + expect_equal(r$Inc_Effect_ref, expected[[s]][[2]], info = s) + expect_equal(r$ICER_ref, expected[[s]][[3]], info = s) + expect_equal(r$Status_ref, expected[[s]][[4]], info = s) + } + expect_type(x$ICER_ref, "double") +}) + +test_that("a dominated or the most expensive strategy can be the reference", { + x <- toy_icers(ref_str = "Worse") + expect_equal(row_of(x, "Worse")$Status_ref, "Reference") + expect_equal(row_of(x, "Cheaper")$Status_ref, "Dominant") + expect_equal(row_of(x, "Cheaper")$Inc_Cost_ref, 50 - 300) + # the frontier itself does not depend on which strategy is the reference + expect_equal(x$Status, toy_icers()$Status) + + y <- toy_icers(ref_str = "Worse") # Worse is also the most expensive strategy + expect_true(all(y$Inc_Cost_ref[y$Strategy != "Worse"] < 0)) +}) + +test_that("NMB is added by default with wtp, NHB only on request", { + x <- toy_icers(wtp = 150) + expect_equal(x$NMB, 150 * x$Effect - x$Cost) + expect_false(any(c("NHB", "iNMB_ref", "iNHB_ref") %in% names(x))) + expect_identical(attr(x, "wtp"), 150) + + y <- toy_icers(ref_str = "Ref", wtp = 150) + expect_equal(row_of(y, "More")$iNMB_ref, (150 * 2 - 200) - (150 * 1 - 100)) + expect_true(is.na(row_of(y, "Ref")$iNMB_ref)) + expect_false("NHB" %in% names(y)) + + z <- toy_icers(ref_str = "Ref", wtp = 150, nhb = TRUE) + expect_equal(z$NHB, z$Effect - z$Cost / 150) + expect_equal(row_of(z, "Cheaper")$iNHB_ref, (1.5 - 50 / 150) - (1 - 100 / 150)) +}) + +test_that("hund_strat: reference columns equal the difference from the reference", { + data("hund_strat") + ref <- hund_strat$Strategy[3] + x <- calculate_icers(hund_strat$Cost, hund_strat$QALYs, hund_strat$Strategy, ref_str = ref) + r0 <- row_of(x, ref) + others <- x$Strategy != ref + expect_equal(x$Inc_Cost_ref[others], x$Cost[others] - r0$Cost) + expect_equal(x$Inc_Effect_ref[others], x$Effect[others] - r0$Effect) +}) + +test_that("edge cases: one strategy, two strategies, names with spaces", { + one <- calculate_icers(10, 1, "Standard of care", ref_str = "Standard of care", wtp = 100) + expect_equal(one$Status_ref, "Reference") + expect_equal(one$NMB, 90) + + two <- calculate_icers(c(10, 30), c(1, 2), c("Standard of care", "New drug (A)"), + ref_str = "Standard of care") + expect_equal(row_of(two, "New drug (A)")$ICER_ref, 20) + expect_equal(row_of(two, "New drug (A)")$Status_ref, "More costly, more effective") +}) + +test_that("invalid ref_str, wtp, and nhb give informative errors", { + expect_error(toy_icers(ref_str = "Nope"), "must be one of the strategies") + expect_error(toy_icers(ref_str = c("Ref", "More")), "single strategy name") + expect_error(toy_icers(wtp = c(100, 200)), "single non-negative number") + expect_error(toy_icers(wtp = -1), "single non-negative number") + expect_error(toy_icers(nhb = TRUE), "requires `wtp`") +}) + +test_that("print.icers shows the sequential table by default and the reference views on request", { + x <- toy_icers(ref_str = "Ref", wtp = 150, currency = "€") + out_seq <- capture.output(print(x)) + expect_true(any(grepl("ICER (€/QALY)", out_seq, fixed = TRUE))) + expect_false(any(grepl("vs Ref", out_seq, fixed = TRUE))) + + out_ref <- capture.output(print(x, ref = "reference")) + expect_true(any(grepl("vs Ref", out_ref, fixed = TRUE))) + expect_false(any(grepl("Incremental Costs (€)", out_ref, fixed = TRUE))) + + out_both <- capture.output(print(x, ref = "both")) + expect_true(any(grepl("vs Ref", out_both, fixed = TRUE))) + expect_true(any(grepl("Incremental Costs (€)", out_both, fixed = TRUE))) + + expect_error(print(toy_icers(), ref = "reference"), "no reference strategy") +}) From fa72c22bb9a25ff309014fca5254e4c54e6942b7 Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Thu, 12 Nov 2026 14:09:50 -0800 Subject: [PATCH 02/10] Plot the incremental CE plane against a reference strategy, with WTP lines - plot.icers() gains ref_str, wtp, ref_axis, and ref_caption (after the existing arguments). ref_str shifts the plot so the reference strategy is at the origin (the frontier and statuses are unchanged); wtp draws a dotted line with slope wtp through the reference, or without ref_str through the least costly frontier strategy. The currency defaults to the one stored by calculate_icers() (#209, #202). - plot.psa() gains wtp, which draws the same line on its incremental plane (requires ref_str) (#202). - plot.psa(ref_str = ) with two strategies: keep a data frame when one comparator is left (drop = FALSE); it failed with "'dims' cannot be of length 0". ref_str is now checked with check_ref_str(). - Captions name the reference and the WTP threshold; this also removes a double space in plot.psa()'s 'Reference Strategy: X' caption. - Tests (test_reference_plots.R) check the plotted coordinates, axis labels, captions, WTP line slope and intercept, currency, the two-strategy case, and the errors. Default plots are unchanged. Part of #209 --- NEWS.md | 2 + R/icers.R | 70 +++++++++++++++++++++++- R/psa.R | 29 +++++++--- man/plot.icers.Rd | 20 ++++++- man/plot.psa.Rd | 8 ++- man/wtp_caption.Rd | 22 ++++++++ tests/testthat/test_reference_plots.R | 79 +++++++++++++++++++++++++++ 7 files changed, 218 insertions(+), 12 deletions(-) create mode 100644 man/wtp_caption.Rd create mode 100644 tests/testthat/test_reference_plots.R diff --git a/NEWS.md b/NEWS.md index 8878a02..534357c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,7 @@ ## New features +- `plot.icers()` gains `ref_str`, which plots the incremental cost-effectiveness plane with the reference strategy at the origin, and `wtp`, which draws a willingness-to-pay line. `plot.psa()` gains `wtp` for the same line on its incremental plane. `plot.icers()` uses the currency stored by `calculate_icers()` (#209, #202). - `calculate_icers()` can compare every strategy with a user-selected reference strategy: with `ref_str = "Standard of care"`, it adds `Inc_Cost_ref`, `Inc_Effect_ref`, `ICER_ref`, and `Status_ref` ("Reference", "Dominant", "Dominated", "More costly, more effective", "Less costly, less effective", or "Equivalent"). The frontier-based results are unchanged, and without `ref_str` no columns are added (#209). - `calculate_icers()` gains `wtp`, which adds the net monetary benefit (`NMB`, and `iNMB_ref` with a reference strategy), and `nhb = TRUE`, which also adds the net health benefit (`NHB`, `iNHB_ref`) (#200). - `calculate_icers()` gains `currency`, used by `print.icers()`. `print.icers()` gains `ref`: `"sequential"` (the default) prints the usual table, and `"reference"` or `"both"` print the comparison with the reference strategy (#209). @@ -24,6 +25,7 @@ ## Bug fixes +- `plot.psa(ref_str = )` now works when there are only two strategies; it used to fail with "'dims' cannot be of length 0" (#209). - `calculate_icers()` with a single strategy now returns a valid `icers` object, with the same columns as for several strategies (`Status` is `"ND"` and the incremental columns are `NA`), so `plot()` and `print()` work on it (#183). - `calculate_icers()` with no strategies now gives an informative error instead of "missing value where TRUE/FALSE needed", and its documentation no longer describes a reference-strategy option that does not exist (#178). - `metamodel()`, and the functions that use it (`owsa()` and `twsa()` on a PSA, `calc_evppi()`, `calc_evsi()`), now work with strategy names that are not syntactically valid R names (#208). diff --git a/R/icers.R b/R/icers.R index 266bb4d..29d7459 100644 --- a/R/icers.R +++ b/R/icers.R @@ -212,6 +212,19 @@ calculate_icers <- function(cost, effect, strategies, ref_str = NULL, wtp = NULL add_reference_and_nmb(df_results, ref_str, wtp, nhb, currency) } +#' Caption text for a willingness-to-pay line +#' +#' @param wtp willingness-to-pay threshold. +#' @param currency currency symbol. +#' @param effect_units units of effectiveness, e.g. \code{"QALYs"}. +#' @return a string such as \code{"Dotted line: WTP = $50,000/QALY"}. +#' @keywords internal +wtp_caption <- function(wtp, currency, effect_units = "QALYs") { + unit <- sub("s$", "", effect_units) + paste0("Dotted line: WTP = ", currency, format(wtp, big.mark = ",", scientific = FALSE, trim = TRUE), + "/", unit) +} + #' Check a reference strategy name #' #' @param ref_str reference strategy name, or \code{NULL}. @@ -424,6 +437,16 @@ compute_icers <- function(non_d) { #' longer strategies are truncated to save space. #' @param plot_frontier_only only plot the efficient frontier #' @param alpha opacity of points +#' @param ref_str name of a reference strategy. If given, the plot shows the incremental +#' cost-effectiveness plane, with the reference strategy at the origin. The frontier and the +#' status of each strategy do not change. Defaults to \code{NULL} (the cost-effectiveness plane). +#' @param wtp a willingness-to-pay threshold. If given, a dotted line with slope \code{wtp} is +#' drawn through the reference strategy (or, without \code{ref_str}, through the least costly +#' strategy on the frontier). Strategies below the line are cost-effective compared with that +#' strategy at this threshold. +#' @param ref_axis with \code{ref_str}, draw dashed axes through the origin. Defaults to \code{TRUE}. +#' @param ref_caption add a caption naming the reference strategy and the WTP threshold. +#' Defaults to \code{TRUE}. #' @inheritParams ggrepel::geom_label_repel #' #' @return a ggplot2 object which can be modified by adding additional geoms @@ -435,7 +458,7 @@ compute_icers <- function(non_d) { #' @export plot.icers <- function(x, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALYs", label = c("frontier", "all", "none"), label_max_char = NULL, @@ -450,8 +473,17 @@ plot.icers <- function(x, xexpand = expansion(0.1), yexpand = expansion(0.1), max.iter = 20000, + ref_str = NULL, + wtp = NULL, + ref_axis = TRUE, + ref_caption = TRUE, ...) { Cost <- Effect <- Status <- Strategy <- Inc_Cost <- Inc_Effect <- ICER <- NULL + if (is.null(currency)) { + currency <- if (is.null(attr(x, "currency"))) "$" else attr(x, "currency") + } + ref_str <- check_ref_str(ref_str, x$Strategy) + check_wtp_nhb(wtp, nhb = FALSE) if (ncol(x) > 7) { # reformat icers class object if uncertainty bounds are present @@ -488,6 +520,23 @@ plot.icers <- function(x, eff_name <- "Effect" cost_name <- "Cost" + # point the WTP line goes through: the reference, or the least costly frontier strategy + if (!is.null(wtp)) { + df_front <- x[x$Status == nd_name, ] + df_anchor <- if (is.null(ref_str)) df_front[which.min(df_front$Cost), ] else x[x$Strategy == ref_str, ] + } + + # incremental plane: put the reference strategy at the origin + x_lab <- paste0("Effect (", effect_units, ")") + y_lab <- paste0("Cost (", currency, ")") + if (!is.null(ref_str)) { + i_ref <- which(x$Strategy == ref_str) + x$Cost <- x$Cost - x$Cost[i_ref] + x$Effect <- x$Effect - x$Effect[i_ref] + x_lab <- paste0("Incremental Effect (", effect_units, ")") + y_lab <- paste0("Incremental Cost (", currency, ")") + } + # frontier only if (plot_frontier_only) { df_plt_data <- x[x$Status == nd_name, ] @@ -502,8 +551,23 @@ plot.icers <- function(x, geom_line(aes(linetype = !!sym(stat_name), group = !!sym(stat_name))) + scale_linetype_manual(name = NULL, values = v_plot_lines) + scale_shape_discrete(name = NULL) + - labs(x = paste0("Effect (", effect_units, ")"), - y = paste0("Cost (", currency, ")")) + labs(x = x_lab, y = y_lab) + + if (!is.null(ref_str) && ref_axis) { + icer_plot <- icer_plot + + geom_hline(yintercept = 0, linetype = "dashed", color = "grey50") + + geom_vline(xintercept = 0, linetype = "dashed", color = "grey50") + } + if (!is.null(wtp)) { + intercept <- if (is.null(ref_str)) df_anchor$Cost - wtp * df_anchor$Effect else 0 + icer_plot <- icer_plot + + geom_abline(intercept = intercept, slope = wtp, linetype = "dotted", color = "grey30") + } + v_caption <- c(if (!is.null(ref_str)) paste0("Reference Strategy: ", ref_str), + if (!is.null(wtp)) wtp_caption(wtp, currency, effect_units)) + if (ref_caption && length(v_caption)) { + icer_plot <- icer_plot + labs(caption = paste(v_caption, collapse = "; ")) + } icer_plot <- add_common_aes(icer_plot, txtsize, col = "none", continuous = c("x", "y"), diff --git a/R/psa.R b/R/psa.R index 2b5a80f..3d64875 100644 --- a/R/psa.R +++ b/R/psa.R @@ -139,7 +139,11 @@ summary.psa <- function(object, calc_sds = FALSE, ...) { #' @param alpha opacity of the scatterplot points. #' 0 is completely transparent, 1 is completely opaque #' @param ref_axis Add dotted axes lines at (0,0). Defaults to TRUE -#' @param ref_caption Add the reference strategy as a caption. Defaults to TRUE +#' @param ref_caption Add the reference strategy (and the WTP threshold, if given) as a caption. +#' Defaults to TRUE +#' @param wtp a willingness-to-pay threshold. If given, a dotted line with slope \code{wtp} is +#' drawn through the origin of the incremental cost-effectiveness plane; samples below the line are +#' cost-effective compared with the reference strategy at this threshold. Requires \code{ref_str}. #' @inheritParams add_common_aes #' #' @importFrom ellipse ellipse @@ -161,6 +165,7 @@ plot.psa <- function(x, ylim = NULL, ref_axis = TRUE, ref_caption = TRUE, + wtp = NULL, ...) { Effectiveness <- Cost <- Strategy <- Eff.mean <- Cost.mean <- y <- group <- NULL @@ -168,6 +173,12 @@ plot.psa <- function(x, df_cost_wide <- x$cost v_strategies <- x$strategies currency <- x$currency + ref_str <- check_ref_str(ref_str, v_strategies) + if (!is.null(wtp) && is.null(ref_str)) { + stop("`wtp` draws a willingness-to-pay line on the incremental cost-effectiveness plane, ", + "so it needs `ref_str`.", call. = FALSE) + } + check_wtp_nhb(wtp, nhb = FALSE) if (is.null(ref_str)) { # expect that effectiveness and costs have strategy column names @@ -236,14 +247,11 @@ plot.psa <- function(x, v_str = v_strategies) } else { - ### Check that the reference strategy is in the list of strategies - if (!(ref_str %in% v_strategies)) { - stop("ref_str must be in the list of strategies") - } ## Function to convert the raw outcomes to incremental outcomes make_df_inc <- function(df) { v_ref <- df[, ref_str] - df_inc <- df[, !(names(df) %in% ref_str)] + # drop = FALSE keeps a data frame when there is a single comparator + df_inc <- df[, !(names(df) %in% ref_str), drop = FALSE] df_inc <- sweep(df_inc, 1, v_ref, "-") df_inc } @@ -281,9 +289,16 @@ plot.psa <- function(x, geom_vline(xintercept = 0, linetype = "dashed", color = "black") } + if (!is.null(wtp)) { + psa_plot <- psa_plot + + geom_abline(intercept = 0, slope = wtp, linetype = "dotted", color = "grey30") + } + if (ref_caption == TRUE) { + v_caption <- c(paste0("Reference Strategy: ", ref_str), + if (!is.null(wtp)) wtp_caption(wtp, currency)) psa_plot <- psa_plot + - labs(caption = paste("Reference Strategy: ", ref_str)) + labs(caption = paste(v_caption, collapse = "; ")) } # define strategy-specific means for the center of the ellipse diff --git a/man/plot.icers.Rd b/man/plot.icers.Rd index 132c482..af2dfdd 100644 --- a/man/plot.icers.Rd +++ b/man/plot.icers.Rd @@ -7,7 +7,7 @@ \method{plot}{icers}( x, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALYs", label = c("frontier", "all", "none"), label_max_char = NULL, @@ -22,6 +22,10 @@ xexpand = expansion(0.1), yexpand = expansion(0.1), max.iter = 20000, + ref_str = NULL, + wtp = NULL, + ref_axis = TRUE, + ref_caption = TRUE, ... ) } @@ -67,6 +71,20 @@ for how to modify this.} \item{max.iter}{Maximum number of iterations to try to resolve overlaps. Defaults to 10000.} +\item{ref_str}{name of a reference strategy. If given, the plot shows the incremental +cost-effectiveness plane, with the reference strategy at the origin. The frontier and the +status of each strategy do not change. Defaults to \code{NULL} (the cost-effectiveness plane).} + +\item{wtp}{a willingness-to-pay threshold. If given, a dotted line with slope \code{wtp} is +drawn through the reference strategy (or, without \code{ref_str}, through the least costly +strategy on the frontier). Strategies below the line are cost-effective compared with that +strategy at this threshold.} + +\item{ref_axis}{with \code{ref_str}, draw dashed axes through the origin. Defaults to \code{TRUE}.} + +\item{ref_caption}{add a caption naming the reference strategy and the WTP threshold. +Defaults to \code{TRUE}.} + \item{...}{further arguments to plot. This is not used by \code{dampack} but required for generic consistency.} } diff --git a/man/plot.psa.Rd b/man/plot.psa.Rd index 32bbf8c..954ba5a 100644 --- a/man/plot.psa.Rd +++ b/man/plot.psa.Rd @@ -20,6 +20,7 @@ ylim = NULL, ref_axis = TRUE, ref_caption = TRUE, + wtp = NULL, ... ) } @@ -56,7 +57,12 @@ will override \code{n_y_ticks} if provided.} \item{ref_axis}{Add dotted axes lines at (0,0). Defaults to TRUE} -\item{ref_caption}{Add the reference strategy as a caption. Defaults to TRUE} +\item{ref_caption}{Add the reference strategy (and the WTP threshold, if given) as a caption. +Defaults to TRUE} + +\item{wtp}{a willingness-to-pay threshold. If given, a dotted line with slope \code{wtp} is +drawn through the origin of the incremental cost-effectiveness plane; samples below the line are +cost-effective compared with the reference strategy at this threshold. Requires \code{ref_str}.} \item{...}{further arguments to plot. This is not used by \code{dampack} but required for generic consistency.} diff --git a/man/wtp_caption.Rd b/man/wtp_caption.Rd new file mode 100644 index 0000000..73b50ab --- /dev/null +++ b/man/wtp_caption.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/icers.R +\name{wtp_caption} +\alias{wtp_caption} +\title{Caption text for a willingness-to-pay line} +\usage{ +wtp_caption(wtp, currency, effect_units = "QALYs") +} +\arguments{ +\item{wtp}{willingness-to-pay threshold.} + +\item{currency}{currency symbol.} + +\item{effect_units}{units of effectiveness, e.g. \code{"QALYs"}.} +} +\value{ +a string such as \code{"Dotted line: WTP = $50,000/QALY"}. +} +\description{ +Caption text for a willingness-to-pay line +} +\keyword{internal} diff --git a/tests/testthat/test_reference_plots.R b/tests/testthat/test_reference_plots.R new file mode 100644 index 0000000..8612bf7 --- /dev/null +++ b/tests/testthat/test_reference_plots.R @@ -0,0 +1,79 @@ +context("reference strategy and WTP lines in plot.icers() and plot.psa() (#209, #202)") + +df_toy <- data.frame(strategy = c("Standard of care", "New drug (A)", "Cheaper", "Worse"), + cost = c(100, 200, 50, 300), + effect = c(1, 2, 1.5, 0.5), + stringsAsFactors = FALSE) +x_toy <- calculate_icers(df_toy$cost, df_toy$effect, df_toy$strategy) + +point_layer <- function(p) { + i <- which(vapply(p$layers, function(l) inherits(l$geom, "GeomPoint"), logical(1)))[1] + ggplot2::layer_data(p, i) +} +abline_layers <- function(p) { + which(vapply(p$layers, function(l) inherits(l$geom, "GeomAbline"), logical(1))) +} + +test_that("plot.icers() is unchanged by default", { + p <- plot(x_toy) + expect_length(abline_layers(p), 0) + expect_equal(p$labels$y, "Cost ($)") + expect_setequal(point_layer(p)$y, df_toy$cost) +}) + +test_that("plot.icers(ref_str = ) puts the reference at the origin", { + p <- plot(x_toy, ref_str = "Standard of care") + d <- point_layer(p) + expect_setequal(d$x, df_toy$effect - 1) + expect_setequal(d$y, df_toy$cost - 100) + expect_equal(p$labels$y, "Incremental Cost ($)") + expect_equal(p$labels$x, "Incremental Effect (QALYs)") + expect_match(p$labels$caption, "Reference Strategy: Standard of care", fixed = TRUE) + expect_error(plot(x_toy, ref_str = "Nope"), "must be one of the strategies") +}) + +test_that("plot.icers(wtp = ) draws the WTP line", { + p_ref <- plot(x_toy, ref_str = "Standard of care", wtp = 150) + i <- abline_layers(p_ref) + expect_length(i, 1) + d <- ggplot2::layer_data(p_ref, i) + expect_equal(d$slope, 150) + expect_equal(d$intercept, 0) + expect_match(p_ref$labels$caption, "WTP = $150/QALY", fixed = TRUE) + + # without a reference, the line goes through the least costly strategy on the frontier + p_abs <- plot(x_toy, wtp = 150) + d <- ggplot2::layer_data(p_abs, abline_layers(p_abs)) + expect_equal(d$intercept, 50 - 150 * 1.5) +}) + +test_that("plot.icers() uses the currency stored by calculate_icers()", { + x_eur <- calculate_icers(df_toy$cost, df_toy$effect, df_toy$strategy, currency = "€") + expect_equal(plot(x_eur)$labels$y, "Cost (€)") + expect_equal(plot(x_eur, currency = "£")$labels$y, "Cost (£)") +}) + +# PSA with two strategies, to cover the drop = FALSE bug in plot.psa(ref_str = ) +set.seed(20261112) +n_sim <- 200 +df_cost2 <- data.frame(A = rnorm(n_sim, 1000, 50), B = rnorm(n_sim, 1500, 50)) +df_eff2 <- data.frame(A = rnorm(n_sim, 1, 0.05), B = rnorm(n_sim, 1.2, 0.05)) +psa_2 <- make_psa_obj(df_cost2, df_eff2, strategies = c("Standard of care", "New drug (A)")) + +test_that("plot.psa(ref_str = ) works with two strategies", { + expect_warning(p <- plot(psa_2, ref_str = "Standard of care"), NA) + d <- point_layer(p) + expect_equal(sort(d$y), sort(df_cost2$B - df_cost2$A)) + expect_equal(sort(d$x), sort(df_eff2$B - df_eff2$A)) +}) + +test_that("plot.psa(wtp = ) draws the WTP line on the incremental plane", { + p <- plot(psa_2, ref_str = "Standard of care", wtp = 2000) + i <- abline_layers(p) + expect_length(i, 1) + expect_equal(ggplot2::layer_data(p, i)$slope, 2000) + expect_match(p$labels$caption, "WTP = $2,000/QALY", fixed = TRUE) + expect_error(plot(psa_2, wtp = 2000), "needs `ref_str`") + expect_error(plot(psa_2, ref_str = "Nope"), "must be one of the strategies") + expect_length(abline_layers(plot(psa_2)), 0) +}) From 481dfa583e314703b8d538c97b1ac0ca4a4d0a7e Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Thu, 12 Nov 2026 14:19:14 -0800 Subject: [PATCH 03/10] Reference strategy and quadrant shares in summary.psa() and calculate_icers_psa() - summary.psa() gains ref_str and wtp (after calc_sds). With ref_str it adds meanIncCost, meanIncEffect, and the share of PSA samples in each quadrant of the incremental CE plane (propNE, propSE, propSW, propNW; NA for the reference). With wtp it adds meanNMB, and with ref_str also meanIncNMB and propCostEffective (share of samples with a higher NMB than the reference) (#209, #202). - calculate_icers_psa() gains ref_str, wtp, and nhb, passed to calculate_icers(). With uncertainty = TRUE and ref_str, it adds 95% intervals of the sample-by-sample differences from the reference (Lower_95_/Upper_95_ for Inc_Cost_ref, Inc_Effect_ref, iNMB_ref). The icers class and attributes are now kept through the uncertainty joins. - print.icers(): every *_ref column belongs to the reference view. - Docs: escape % in roxygen. An unescaped % starts an Rd comment, which had silently truncated ?calculate_icers_psa ('whether or not 95') and ?predict.metamodel. calculate_icers_psa() output for existing calls is identical to main's (objects, class, and printed tables, with and without uncertainty). Part of #209. Closes #202 --- NEWS.md | 2 + R/icers.R | 62 +++++++++++++++++++++-- R/metamodel.R | 2 +- R/psa.R | 44 ++++++++++++++++- man/add_reference_intervals.Rd | 30 +++++++++++ man/calculate_icers_psa.Rd | 27 +++++++++- man/owsa.Rd | 2 +- man/predict.metamodel.Rd | 2 +- man/summary.psa.Rd | 20 +++++++- man/twsa.Rd | 2 +- tests/testthat/test_psa_reference.R | 77 +++++++++++++++++++++++++++++ 11 files changed, 257 insertions(+), 13 deletions(-) create mode 100644 man/add_reference_intervals.Rd create mode 100644 tests/testthat/test_psa_reference.R diff --git a/NEWS.md b/NEWS.md index 534357c..39f373c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,8 @@ ## New features +- `summary.psa()` gains `ref_str` and `wtp`. With a reference strategy it adds the mean incremental cost and effect and the proportion of PSA samples in each quadrant of the incremental cost-effectiveness plane (`propNE`, `propSE`, `propSW`, `propNW`); with `wtp` it adds the mean NMB and, with a reference, `meanIncNMB` and the proportion of samples that are cost-effective compared with the reference (`propCostEffective`) (#209, #202). +- `calculate_icers_psa()` gains `ref_str`, `wtp`, and `nhb`. With `uncertainty = TRUE` and a reference strategy, it adds 95% intervals for the differences from the reference, computed sample by sample (#209). - `plot.icers()` gains `ref_str`, which plots the incremental cost-effectiveness plane with the reference strategy at the origin, and `wtp`, which draws a willingness-to-pay line. `plot.psa()` gains `wtp` for the same line on its incremental plane. `plot.icers()` uses the currency stored by `calculate_icers()` (#209, #202). - `calculate_icers()` can compare every strategy with a user-selected reference strategy: with `ref_str = "Standard of care"`, it adds `Inc_Cost_ref`, `Inc_Effect_ref`, `ICER_ref`, and `Status_ref` ("Reference", "Dominant", "Dominated", "More costly, more effective", "Less costly, less effective", or "Equivalent"). The frontier-based results are unchanged, and without `ref_str` no columns are added (#209). - `calculate_icers()` gains `wtp`, which adds the net monetary benefit (`NMB`, and `iNMB_ref` with a reference strategy), and `nhb = TRUE`, which also adds the net health benefit (`NHB`, `iNHB_ref`) (#200). diff --git a/R/icers.R b/R/icers.R index 29d7459..98db64c 100644 --- a/R/icers.R +++ b/R/icers.R @@ -340,18 +340,25 @@ add_reference_and_nmb <- function(df_icers, ref_str, wtp, nhb, currency) { #' even if present in the ICER table. #' #' @param psa \code{psa} object from \code{link{make_psa_object}} -#' @param uncertainty whether or not 95% quantiles for the cost and QALY outcomes should be included +#' @param uncertainty whether or not 95\% quantiles for the cost and QALY outcomes should be included #' in the resulting ICER table. Defaults to \code{FALSE}. +#' @inheritParams calculate_icers #' #' @return A data frame and \code{icers} object of strategies and their associated #' status, cost, effect, incremental cost, incremental effect, and ICER. If \code{uncertainty} is #' set to \code{TRUE}, four additional columns are provided for the 2.5th and 97.5th quantiles for #' each strategy's cost and effect. +#' +#' With \code{ref_str}, \code{wtp}, or \code{nhb}, the reference-strategy and net-benefit columns +#' described in \code{\link{calculate_icers}} are added. With \code{uncertainty = TRUE} and +#' \code{ref_str}, the 2.5th and 97.5th quantiles of the sample-by-sample differences from the reference +#' are also given for \code{Inc_Cost_ref}, \code{Inc_Effect_ref}, and (with \code{wtp}) +#' \code{iNMB_ref}, in columns such as \code{Lower_95_Inc_Cost_ref} and \code{Upper_95_Inc_Cost_ref}. #' @seealso \code{\link{plot.icers}} #' @seealso \code{\link{calculate_icers}} #' @importFrom tidyr pivot_longer #' @export -calculate_icers_psa <- function(psa, uncertainty = FALSE) { +calculate_icers_psa <- function(psa, uncertainty = FALSE, ref_str = NULL, wtp = NULL, nhb = FALSE) { # check that psa has class 'psa' check_psa_object(psa) @@ -365,9 +372,13 @@ calculate_icers_psa <- function(psa, uncertainty = FALSE) { # Supply mean outcome values to calculate_icers df_icers <- calculate_icers(cost = df_psa_sum$meanCost, effect = df_psa_sum$meanEffect, - strategies = df_psa_sum$Strategy) + strategies = df_psa_sum$Strategy, + ref_str = ref_str, wtp = wtp, nhb = nhb) if (uncertainty == TRUE) { + # the joins and column selection below drop the icers class and attributes; keep them + l_attr <- attributes(df_icers)[c("class", "ref_str", "wtp", "currency")] + l_attr <- l_attr[!vapply(l_attr, is.null, logical(1))] # extract cost and effect data.frames from psa object df_cost <- psa$cost @@ -392,12 +403,53 @@ calculate_icers_psa <- function(psa, uncertainty = FALSE) { left_join(df_effect_bounds, by = "Strategy") %>% select(Strategy, Cost, Lower_95_Cost, Upper_95_Cost, Effect, Lower_95_Effect, Upper_95_Effect, - Inc_Cost, Inc_Effect, ICER, Status) + Inc_Cost, Inc_Effect, ICER, Status, everything()) + + if (!is.null(ref_str)) { + df_icers <- add_reference_intervals(df_icers, psa, ref_str, wtp) + } + df_icers <- as.data.frame(df_icers) + for (a in names(l_attr)) { + attr(df_icers, a) <- l_attr[[a]] + } } df_icers } +#' Add 95\% intervals for the differences from a reference strategy +#' +#' Quantiles of the sample-by-sample differences between each strategy and the reference, placed +#' after the corresponding point estimate. \code{NA} for the reference itself. +#' +#' @param df_icers an \code{icers} object with reference columns. +#' @param psa the \code{psa} object it was computed from. +#' @inheritParams calculate_icers +#' @return \code{df_icers} with the interval columns added. +#' @keywords internal +add_reference_intervals <- function(df_icers, psa, ref_str, wtp) { + m_inc_cost <- as.matrix(psa$cost) - psa$cost[[ref_str]] + m_inc_effect <- as.matrix(psa$effectiveness) - psa$effectiveness[[ref_str]] + l_inc <- list(Inc_Cost_ref = m_inc_cost, Inc_Effect_ref = m_inc_effect) + if (!is.null(wtp)) { + l_inc$iNMB_ref <- wtp * m_inc_effect - m_inc_cost + } + v_strat <- df_icers$Strategy + v_cols <- names(df_icers) + for (col in names(l_inc)) { + m_inc <- l_inc[[col]][, v_strat, drop = FALSE] + v_lower <- unname(apply(m_inc, 2, quantile, probs = 0.025, names = FALSE)) + v_upper <- unname(apply(m_inc, 2, quantile, probs = 0.975, names = FALSE)) + v_lower[v_strat == ref_str] <- NA_real_ + v_upper[v_strat == ref_str] <- NA_real_ + df_icers[[paste0("Lower_95_", col)]] <- v_lower + df_icers[[paste0("Upper_95_", col)]] <- v_upper + i <- match(col, v_cols) + v_cols <- append(v_cols, paste0(c("Lower_95_", "Upper_95_"), col), after = i) + } + df_icers[, v_cols] +} + #' compute icers for non-dominated strategies #' #' @param non_d a data frame of non-dominated strategies, with columns @@ -656,7 +708,7 @@ print.icers <- function(x, # columns that belong to each view v_seq_cols <- c("Inc_Cost", "Inc_Effect", "ICER", "Status") - v_ref_cols <- c("Inc_Cost_ref", "Inc_Effect_ref", "ICER_ref", "Status_ref", "iNMB_ref", "iNHB_ref") + v_ref_cols <- grep("_ref$", names(x), value = TRUE) v_drop <- switch(ref, sequential = v_ref_cols, reference = v_seq_cols, both = character(0)) df_table_cea <- x class(df_table_cea) <- "data.frame" diff --git a/R/metamodel.R b/R/metamodel.R index 9767350..c8491a0 100644 --- a/R/metamodel.R +++ b/R/metamodel.R @@ -303,7 +303,7 @@ summary.metamodel <- function(object, ...) { #' @param object object with class "metamodel" #' @param ranges a named list of the form c("param" = c(0, 1), ...) #' that gives the ranges for the parameter of interest. If NULL, -#' parameter values from the middle 95% of the PSA samples are used. The number of samples +#' parameter values from the middle 95\% of the PSA samples are used. The number of samples #' from this range is determined by \code{nsamp}. #' @param nsamp number of samples from ranges #' @param ... further arguments to \code{predict} (not used) diff --git a/R/psa.R b/R/psa.R index 3d64875..f2def64 100644 --- a/R/psa.R +++ b/R/psa.R @@ -104,13 +104,31 @@ check_df_and_coerce <- function(obj) { #' #' @param object the psa object #' @param calc_sds whether or not to calculate the standard deviations. Defaults to FALSE +#' @param ref_str name of a reference strategy. If given, each strategy is compared with it +#' sample by sample (see Value). Defaults to \code{NULL}. +#' @param wtp a single willingness-to-pay threshold. If given, the mean net monetary benefit is +#' added (see Value). Defaults to \code{NULL}. #' @param ... further arguments to summary (not used) #' #' @importFrom stats sd #' @return a \code{data.frame} containing the mean cost and effectiveness for each strategy and, if requested, #' the standard deviations of the cost and effectiveness for each strategy. +#' +#' With \code{ref_str}, the differences between each strategy and the reference are computed in +#' every PSA sample, and these columns are added (\code{NA} for the reference itself): +#' \code{meanIncCost} and \code{meanIncEffect}, the mean differences in cost and effect; and +#' \code{propNE}, \code{propSE}, \code{propSW}, and \code{propNW}, the proportion of samples in each +#' quadrant of the incremental cost-effectiveness plane: NE more effective and more costly, SE more +#' effective and not more costly (dominant), SW not more effective and not more costly, and NW not more +#' effective and more costly (dominated). The four proportions sum to 1. +#' +#' With \code{wtp}, \code{meanNMB} (\code{wtp * effect - cost}, averaged over samples) is added; with +#' \code{ref_str} too, also \code{meanIncNMB} and \code{propCostEffective}, the proportion of samples in +#' which the strategy has a higher NMB than the reference (it lies below the willingness-to-pay line). #' @export -summary.psa <- function(object, calc_sds = FALSE, ...) { +summary.psa <- function(object, calc_sds = FALSE, ref_str = NULL, wtp = NULL, ...) { + ref_str <- check_ref_str(ref_str, object$strategies) + check_wtp_nhb(wtp, nhb = FALSE) v_mean_cost <- colMeans(object$cost) v_mean_effect <- colMeans(object$effectiveness) @@ -125,6 +143,30 @@ summary.psa <- function(object, calc_sds = FALSE, ...) { df_sum_psa[, "sdCost"] <- v_sd_cost df_sum_psa[, "sdEffect"] <- v_sd_effect } + if (!is.null(wtp)) { + df_sum_psa[, "meanNMB"] <- unname(colMeans(wtp * object$effectiveness - object$cost)) + } + if (!is.null(ref_str)) { + # sample-by-sample differences from the reference strategy + m_inc_cost <- as.matrix(object$cost) - object$cost[[ref_str]] + m_inc_effect <- as.matrix(object$effectiveness) - object$effectiveness[[ref_str]] + v_is_ref <- v_strat == ref_str + na_ref <- function(v) { + v[v_is_ref] <- NA_real_ + unname(v) + } + df_sum_psa[, "meanIncCost"] <- na_ref(colMeans(m_inc_cost)) + df_sum_psa[, "meanIncEffect"] <- na_ref(colMeans(m_inc_effect)) + df_sum_psa[, "propNE"] <- na_ref(colMeans(m_inc_effect > 0 & m_inc_cost > 0)) + df_sum_psa[, "propSE"] <- na_ref(colMeans(m_inc_effect > 0 & m_inc_cost <= 0)) + df_sum_psa[, "propSW"] <- na_ref(colMeans(m_inc_effect <= 0 & m_inc_cost <= 0)) + df_sum_psa[, "propNW"] <- na_ref(colMeans(m_inc_effect <= 0 & m_inc_cost > 0)) + if (!is.null(wtp)) { + m_inc_nmb <- wtp * m_inc_effect - m_inc_cost + df_sum_psa[, "meanIncNMB"] <- na_ref(colMeans(m_inc_nmb)) + df_sum_psa[, "propCostEffective"] <- na_ref(colMeans(m_inc_nmb > 0)) + } + } rownames(df_sum_psa) <- seq_len(nrow(df_sum_psa)) df_sum_psa } diff --git a/man/add_reference_intervals.Rd b/man/add_reference_intervals.Rd new file mode 100644 index 0000000..45abbf9 --- /dev/null +++ b/man/add_reference_intervals.Rd @@ -0,0 +1,30 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/icers.R +\name{add_reference_intervals} +\alias{add_reference_intervals} +\title{Add 95\% intervals for the differences from a reference strategy} +\usage{ +add_reference_intervals(df_icers, psa, ref_str, wtp) +} +\arguments{ +\item{df_icers}{an \code{icers} object with reference columns.} + +\item{psa}{the \code{psa} object it was computed from.} + +\item{ref_str}{name of a reference strategy (one of \code{strategies}) to compare every +strategy against, for example \code{"Standard of care"}. The default (\code{NULL}) adds no +reference columns. The frontier-based results (\code{Status}, \code{Inc_Cost}, +\code{Inc_Effect}, \code{ICER}) never depend on the reference.} + +\item{wtp}{a single willingness-to-pay threshold (currency per unit of effect). If given, +the net monetary benefit (\code{NMB}) of each strategy is added. The default (\code{NULL}) +adds no net-benefit columns.} +} +\value{ +\code{df_icers} with the interval columns added. +} +\description{ +Quantiles of the sample-by-sample differences between each strategy and the reference, placed +after the corresponding point estimate. \code{NA} for the reference itself. +} +\keyword{internal} diff --git a/man/calculate_icers_psa.Rd b/man/calculate_icers_psa.Rd index 14b56d8..e5cfc61 100644 --- a/man/calculate_icers_psa.Rd +++ b/man/calculate_icers_psa.Rd @@ -4,19 +4,42 @@ \alias{calculate_icers_psa} \title{Calculate incremental cost-effectiveness ratios from a \code{psa} object.} \usage{ -calculate_icers_psa(psa, uncertainty = FALSE) +calculate_icers_psa( + psa, + uncertainty = FALSE, + ref_str = NULL, + wtp = NULL, + nhb = FALSE +) } \arguments{ \item{psa}{\code{psa} object from \code{link{make_psa_object}}} -\item{uncertainty}{whether or not 95% quantiles for the cost and QALY outcomes should be included +\item{uncertainty}{whether or not 95\% quantiles for the cost and QALY outcomes should be included in the resulting ICER table. Defaults to \code{FALSE}.} + +\item{ref_str}{name of a reference strategy (one of \code{strategies}) to compare every +strategy against, for example \code{"Standard of care"}. The default (\code{NULL}) adds no +reference columns. The frontier-based results (\code{Status}, \code{Inc_Cost}, +\code{Inc_Effect}, \code{ICER}) never depend on the reference.} + +\item{wtp}{a single willingness-to-pay threshold (currency per unit of effect). If given, +the net monetary benefit (\code{NMB}) of each strategy is added. The default (\code{NULL}) +adds no net-benefit columns.} + +\item{nhb}{if \code{TRUE}, also add the net health benefit (\code{NHB}). Requires \code{wtp}.} } \value{ A data frame and \code{icers} object of strategies and their associated status, cost, effect, incremental cost, incremental effect, and ICER. If \code{uncertainty} is set to \code{TRUE}, four additional columns are provided for the 2.5th and 97.5th quantiles for each strategy's cost and effect. + +With \code{ref_str}, \code{wtp}, or \code{nhb}, the reference-strategy and net-benefit columns +described in \code{\link{calculate_icers}} are added. With \code{uncertainty = TRUE} and +\code{ref_str}, the 2.5th and 97.5th quantiles of the sample-by-sample differences from the reference +are also given for \code{Inc_Cost_ref}, \code{Inc_Effect_ref}, and (with \code{wtp}) +\code{iNMB_ref}, in columns such as \code{Lower_95_Inc_Cost_ref} and \code{Upper_95_Inc_Cost_ref}. } \description{ The mean costs and QALYs for each strategy in a PSA are used diff --git a/man/owsa.Rd b/man/owsa.Rd index 422fa56..ea18fec 100644 --- a/man/owsa.Rd +++ b/man/owsa.Rd @@ -24,7 +24,7 @@ a deterministic sensitivity analysis object (\code{\link{run_owsa_det}})} \item{ranges}{a named list of the form c("param" = c(0, 1), ...) that gives the ranges for the parameter of interest. If NULL, -parameter values from the middle 95% of the PSA samples are used. The number of samples +parameter values from the middle 95\% of the PSA samples are used. The number of samples from this range is determined by \code{nsamp}.} \item{nsamp}{number of samples to take from the ranges} diff --git a/man/predict.metamodel.Rd b/man/predict.metamodel.Rd index 918d2ba..ec60a1d 100644 --- a/man/predict.metamodel.Rd +++ b/man/predict.metamodel.Rd @@ -11,7 +11,7 @@ \item{ranges}{a named list of the form c("param" = c(0, 1), ...) that gives the ranges for the parameter of interest. If NULL, -parameter values from the middle 95% of the PSA samples are used. The number of samples +parameter values from the middle 95\% of the PSA samples are used. The number of samples from this range is determined by \code{nsamp}.} \item{nsamp}{number of samples from ranges} diff --git a/man/summary.psa.Rd b/man/summary.psa.Rd index 9251f93..ca0a145 100644 --- a/man/summary.psa.Rd +++ b/man/summary.psa.Rd @@ -4,18 +4,36 @@ \alias{summary.psa} \title{summarize a psa object across all simulations} \usage{ -\method{summary}{psa}(object, calc_sds = FALSE, ...) +\method{summary}{psa}(object, calc_sds = FALSE, ref_str = NULL, wtp = NULL, ...) } \arguments{ \item{object}{the psa object} \item{calc_sds}{whether or not to calculate the standard deviations. Defaults to FALSE} +\item{ref_str}{name of a reference strategy. If given, each strategy is compared with it +sample by sample (see Value). Defaults to \code{NULL}.} + +\item{wtp}{a single willingness-to-pay threshold. If given, the mean net monetary benefit is +added (see Value). Defaults to \code{NULL}.} + \item{...}{further arguments to summary (not used)} } \value{ a \code{data.frame} containing the mean cost and effectiveness for each strategy and, if requested, the standard deviations of the cost and effectiveness for each strategy. + +With \code{ref_str}, the differences between each strategy and the reference are computed in +every PSA sample, and these columns are added (\code{NA} for the reference itself): +\code{meanIncCost} and \code{meanIncEffect}, the mean differences in cost and effect; and +\code{propNE}, \code{propSE}, \code{propSW}, and \code{propNW}, the proportion of samples in each +quadrant of the incremental cost-effectiveness plane: NE more effective and more costly, SE more +effective and not more costly (dominant), SW not more effective and not more costly, and NW not more +effective and more costly (dominated). The four proportions sum to 1. + +With \code{wtp}, \code{meanNMB} (\code{wtp * effect - cost}, averaged over samples) is added; with +\code{ref_str} too, also \code{meanIncNMB} and \code{propCostEffective}, the proportion of samples in +which the strategy has a higher NMB than the reference (it lies below the willingness-to-pay line). } \description{ summarize a psa object across all simulations diff --git a/man/twsa.Rd b/man/twsa.Rd index c167cd7..9c5f0a3 100644 --- a/man/twsa.Rd +++ b/man/twsa.Rd @@ -27,7 +27,7 @@ a deterministic sensitivity analysis object (\code{\link{run_owsa_det}})} \item{ranges}{a named list of the form c("param" = c(0, 1), ...) that gives the ranges for the parameter of interest. If NULL, -parameter values from the middle 95% of the PSA samples are used. The number of samples +parameter values from the middle 95\% of the PSA samples are used. The number of samples from this range is determined by \code{nsamp}.} \item{nsamp}{number of samples from ranges} diff --git a/tests/testthat/test_psa_reference.R b/tests/testthat/test_psa_reference.R new file mode 100644 index 0000000..79e0f2b --- /dev/null +++ b/tests/testthat/test_psa_reference.R @@ -0,0 +1,77 @@ +context("summary.psa() and calculate_icers_psa() against a reference strategy (#209, #202)") + +# Four PSA samples; the difference "New" - "Ref" falls in a different quadrant in each: +# sample inc effect inc cost quadrant +# 1 +0.2 +100 NE (more effective, more costly) +# 2 +0.2 -50 SE (more effective, less costly) +# 3 -0.1 -50 SW (less effective, less costly) +# 4 -0.1 +100 NW (less effective, more costly) +df_cost <- data.frame(Ref = c(1000, 1000, 1000, 1000), New = c(1100, 950, 950, 1100)) +df_eff <- data.frame(Ref = c(1, 1, 1, 1), New = c(1.2, 1.2, 0.9, 0.9)) +psa_q <- make_psa_obj(df_cost, df_eff, strategies = c("Ref", "New")) + +test_that("summary.psa() is unchanged without ref_str and wtp", { + expect_identical(names(summary(psa_q)), c("Strategy", "meanCost", "meanEffect")) +}) + +test_that("summary.psa(ref_str = ) gives mean differences and quadrant shares", { + s <- summary(psa_q, ref_str = "Ref") + r_new <- s[s$Strategy == "New", ] + r_ref <- s[s$Strategy == "Ref", ] + expect_equal(r_new$meanIncCost, mean(df_cost$New - df_cost$Ref)) + expect_equal(r_new$meanIncEffect, mean(df_eff$New - df_eff$Ref)) + expect_equal(unlist(r_new[, c("propNE", "propSE", "propSW", "propNW")], use.names = FALSE), + rep(0.25, 4)) + expect_true(all(is.na(r_ref[, c("meanIncCost", "meanIncEffect", "propNE", "propSE", "propSW", "propNW")]))) + expect_error(summary(psa_q, ref_str = "Nope"), "must be one of the strategies") +}) + +test_that("summary.psa(wtp = ) gives mean NMB and the share of cost-effective samples", { + s <- summary(psa_q, wtp = 1000) + expect_equal(s$meanNMB, unname(1000 * colMeans(df_eff) - colMeans(df_cost))) + expect_false(any(c("meanIncNMB", "propCostEffective") %in% names(s))) + + s_ref <- summary(psa_q, ref_str = "Ref", wtp = 1000) + inmb <- 1000 * (df_eff$New - df_eff$Ref) - (df_cost$New - df_cost$Ref) # 100, 250, -50, -200 + r_new <- s_ref[s_ref$Strategy == "New", ] + expect_equal(r_new$meanIncNMB, mean(inmb)) + expect_equal(r_new$propCostEffective, mean(inmb > 0)) + expect_equal(r_new$propCostEffective, 0.5) +}) + +data("cancer_psa_data") +psa_big <- make_psa_obj(cancer_psa_data$cost, cancer_psa_data$effectiveness, + cancer_psa_data$parameters, c("Chemotherapy", "Radiation therapy", "Surgery")) + +test_that("calculate_icers_psa() passes ref_str, wtp, and nhb to calculate_icers()", { + s <- summary(psa_big) + expected <- calculate_icers(s$meanCost, s$meanEffect, s$Strategy, + ref_str = "Surgery", wtp = 50000, nhb = TRUE) + obtained <- calculate_icers_psa(psa_big, ref_str = "Surgery", wtp = 50000, nhb = TRUE) + expect_equal(obtained, expected) +}) + +test_that("calculate_icers_psa(uncertainty = TRUE) adds intervals for the reference comparison", { + x <- calculate_icers_psa(psa_big, uncertainty = TRUE, ref_str = "Surgery", wtp = 50000) + expect_identical(attr(x, "ref_str"), "Surgery") + r <- x[x$Strategy == "Chemotherapy", ] + d_cost <- cancer_psa_data$cost[[1]] - cancer_psa_data$cost[[3]] + d_eff <- cancer_psa_data$effectiveness[[1]] - cancer_psa_data$effectiveness[[3]] + expect_equal(r$Lower_95_Inc_Cost_ref, unname(quantile(d_cost, 0.025))) + expect_equal(r$Upper_95_Inc_Cost_ref, unname(quantile(d_cost, 0.975))) + expect_equal(r$Lower_95_Inc_Effect_ref, unname(quantile(d_eff, 0.025))) + expect_equal(r$Upper_95_iNMB_ref, unname(quantile(50000 * d_eff - d_cost, 0.975))) + r_ref <- x[x$Strategy == "Surgery", ] + expect_true(is.na(r_ref$Lower_95_Inc_Cost_ref)) + # the frontier-based columns and their existing intervals are unchanged + x0 <- calculate_icers_psa(psa_big, uncertainty = TRUE) + expect_equal(as.data.frame(x)[, names(x0)], as.data.frame(x0)) +}) + +test_that("print.icers() keeps reference intervals out of the sequential view", { + x <- calculate_icers_psa(psa_big, uncertainty = TRUE, ref_str = "Surgery") + out_seq <- capture.output(print(x)) + expect_false(any(grepl("Inc_Cost_ref", out_seq, fixed = TRUE))) + out_ref <- capture.output(print(x, ref = "reference")) + expect_true(any(grepl("Lower_95_Inc_Cost_ref", out_ref, fixed = TRUE))) +}) From 3886a043d549473b81c50a9535b2e928abd13033 Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Fri, 13 Nov 2026 07:10:18 -0800 Subject: [PATCH 04/10] Carry the currency of a psa object through to its analyses - ceac(), calc_exp_loss(), calc_evpi(), calc_evppi(), calc_evsi(), and calculate_icers_psa() store psa$currency on their results. - Their plot() methods (and print.icers()) use it: currency defaults to NULL, resolved by resolve_currency() as the argument if given, else the result's currency, else '$'. Existing calls keep working. - plot.ceac() gains effect_units (the x-axis label hard-coded QALY). - EVPPI and EVSI computed from net health benefit are in health units: calc_evppi() and calc_evsi() store the outcome, and their plots are labeled 'EVPPI (QALY)' / 'EVSI (QALY)' instead of a currency. calc_evsi() defaults to outcome = 'nhb', so its default plot was mislabeled in dollars. - Tests (test_currency.R) with a euro PSA for every function, overrides, effect_units, and dollar defaults; two existing tests now build the expected object with the same currency. Outputs of all vignettes and examples change only by the new currency attribute; values, plot data, and labels are unchanged. Closes #203 --- NEWS.md | 2 + R/add_common_aes.R | 27 ++++++++++++++ R/ceac.R | 11 ++++-- R/evpi.R | 7 +++- R/evppi.R | 12 ++++-- R/evsi.R | 12 ++++-- R/exp_loss.R | 7 +++- R/icers.R | 3 +- man/plot.ceac.Rd | 8 +++- man/plot.evpi.Rd | 5 ++- man/plot.evppi.Rd | 5 ++- man/plot.evsi.Rd | 5 ++- man/plot.exp_loss.Rd | 5 ++- man/resolve_currency.Rd | 20 ++++++++++ man/voi_units.Rd | 23 ++++++++++++ tests/testthat/test_calculate_icers.R | 3 +- tests/testthat/test_currency.R | 54 +++++++++++++++++++++++++++ tests/testthat/test_psa_reference.R | 4 +- 18 files changed, 186 insertions(+), 27 deletions(-) create mode 100644 man/resolve_currency.Rd create mode 100644 man/voi_units.Rd create mode 100644 tests/testthat/test_currency.R diff --git a/NEWS.md b/NEWS.md index ca145e2..e50e381 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,7 @@ ## New features +- The currency of a `psa` object now carries through to its analyses: `ceac()`, `calc_exp_loss()`, `calc_evpi()`, `calc_evppi()`, `calc_evsi()`, and `calculate_icers_psa()` keep it, and their `plot()` and `print()` methods use it unless `currency` is given. `plot.ceac()` gains `effect_units` (#203). - `summary.psa()` gains `ref_str` and `wtp`. With a reference strategy it adds the mean incremental cost and effect and the proportion of PSA samples in each quadrant of the incremental cost-effectiveness plane (`propNE`, `propSE`, `propSW`, `propNW`); with `wtp` it adds the mean NMB and, with a reference, `meanIncNMB` and the proportion of samples that are cost-effective compared with the reference (`propCostEffective`) (#209, #202). - `calculate_icers_psa()` gains `ref_str`, `wtp`, and `nhb`. With `uncertainty = TRUE` and a reference strategy, it adds 95% intervals for the differences from the reference, computed sample by sample (#209). - `plot.icers()` gains `ref_str`, which plots the incremental cost-effectiveness plane with the reference strategy at the origin, and `wtp`, which draws a willingness-to-pay line. `plot.psa()` gains `wtp` for the same line on its incremental plane. `plot.icers()` uses the currency stored by `calculate_icers()` (#209, #202). @@ -27,6 +28,7 @@ ## Bug fixes +- EVPPI and EVSI computed from net health benefit (`outcome = "nhb"`, the default of `calc_evsi()`) are in health units, and their plots are now labeled with `effect_units` (e.g., "EVSI (QALY)") instead of a currency (#203). - `plot.psa(ref_str = )` now works when there are only two strategies; it used to fail with "'dims' cannot be of length 0" (#209). - `plot.owsa(col = "bw")` now draws each strategy with its own line type; all strategies used to share one line type and could not be told apart (#176). - `metamodel()` now names invalid parameters in its error message, including when called through `calc_evppi()` and `calc_evsi()` (#177). diff --git a/R/add_common_aes.R b/R/add_common_aes.R index fb29d4f..e3467d9 100644 --- a/R/add_common_aes.R +++ b/R/add_common_aes.R @@ -251,3 +251,30 @@ number_ticks <- function(n) { pretty(limits, n + 1) } } + +#' Currency to use for labels +#' +#' @param currency currency given by the user, or \code{NULL}. +#' @param x a result object that may carry a \code{"currency"} attribute. +#' @return \code{currency} if given, otherwise the currency stored on \code{x}, otherwise \code{"$"}. +#' @keywords internal +resolve_currency <- function(currency, x) { + if (!is.null(currency)) { + return(currency) + } + if (is.null(attr(x, "currency"))) "$" else attr(x, "currency") +} + +#' Units of a value-of-information result +#' +#' EVPPI and EVSI computed from net health benefit are in health units; from net monetary +#' benefit, in currency. +#' +#' @param x an \code{evppi} or \code{evsi} object. +#' @param currency currency label. +#' @param effect_units units of effectiveness. +#' @return \code{effect_units} if \code{x} was computed with \code{outcome = "nhb"}, else \code{currency}. +#' @keywords internal +voi_units <- function(x, currency, effect_units) { + if (identical(attr(x, "outcome"), "nhb")) effect_units else currency +} diff --git a/R/ceac.R b/R/ceac.R index 38a8e92..8b83c0a 100644 --- a/R/ceac.R +++ b/R/ceac.R @@ -122,6 +122,7 @@ ceac <- function(wtp, psa) { # define classes # defining data.frame as well allows the object to use print.data.frame, for example class(ceac) <- c("ceac", "data.frame") + attr(ceac, "currency") <- psa$currency ceac } @@ -134,7 +135,9 @@ ceac <- function(wtp, psa) { #' @param frontier whether to plot acceptability frontier (TRUE) or not (FALSE) #' @param points whether to plot points (TRUE) or not (FALSE) #' @param currency string with currency used in the cost-effectiveness analysis (CEA). -#'Defaults to \code{$}, but can be any currency symbol or word (e.g., £, €, peso) +#' Defaults to the currency of the PSA the CEAC was computed from (or \code{$}), but can be any +#' currency symbol or word (e.g., £, €, peso). +#' @param effect_units units of effectiveness, used in the x-axis label. Default: QALY #' @param min_prob minimum probability to show strategy in plot. #' For example, if the min_prob is 0.05, only strategies that ever #' exceed Pr(Cost Effective) = 0.05 will be plotted. Most useful in situations @@ -157,7 +160,7 @@ ceac <- function(wtp, psa) { plot.ceac <- function(x, frontier = TRUE, points = TRUE, - currency = "$", + currency = NULL, min_prob = 0, txtsize = 12, n_x_ticks = 10, @@ -167,7 +170,9 @@ plot.ceac <- function(x, ylim = NULL, xlim = c(0, NA), col = c("access", "full", "bw"), + effect_units = "QALY", ...) { + currency <- resolve_currency(currency, x) wtp_name <- "WTP" prop_name <- "Proportion" strat_name <- "Strategy" @@ -217,7 +222,7 @@ plot.ceac <- function(x, y = !!sym(prop_name), color = !!sym(strat_name))) + geom_line() + - xlab(paste("Willingness to Pay (Thousand ", currency, " / QALY)", sep = "")) + + xlab(paste("Willingness to Pay (Thousand ", currency, " / ", effect_units, ")", sep = "")) + ylab("Pr Most Cost-Effective") if (points) { diff --git a/R/evpi.R b/R/evpi.R index 3643300..be85414 100644 --- a/R/evpi.R +++ b/R/evpi.R @@ -55,6 +55,7 @@ calc_evpi <- function(psa, wtp, pop = 1) { # declare class as both evpi (plotting) and data.frame (printing) class(df_evpi) <- c("evpi", "data.frame") + attr(df_evpi, "currency") <- psa$currency df_evpi } @@ -66,7 +67,8 @@ calc_evpi <- function(psa, wtp, pop = 1) { #' @param x object of class \code{evpi}, produced by function #' \code{\link{calc_evpi}} #' @param currency string with currency used in the cost-effectiveness analysis (CEA). -#' Default: $, but it could be any currency symbol or word (e.g., £, €, peso) +#' Default: the currency of the PSA the results were computed from (or $), but it could be any +#' currency symbol or word (e.g., £, €, peso) #' @param effect_units units of effectiveness. Default: QALY #' @inheritParams add_common_aes #' @keywords expected value of perfect information @@ -77,7 +79,7 @@ calc_evpi <- function(psa, wtp, pop = 1) { #' @export plot.evpi <- function(x, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALY", n_y_ticks = 8, n_x_ticks = 20, @@ -87,6 +89,7 @@ plot.evpi <- function(x, ylim = NULL, ...) { WTP_thou <- EVPI <- NULL + currency <- resolve_currency(currency, x) x$WTP_thou <- x$WTP / 1000 g <- ggplot(data = x, aes(x = WTP_thou, y = EVPI)) + diff --git a/R/evppi.R b/R/evppi.R index 74b5ae6..44e95a7 100644 --- a/R/evppi.R +++ b/R/evppi.R @@ -78,6 +78,7 @@ calc_evppi <- function(psa, # define parameter values and make sure they correspond to a valid option type <- match.arg(type) outcome <- match.arg(outcome) + outcome_input <- outcome # adjust outcome type outcome <- paste0(outcome, "_loss_voi") @@ -127,6 +128,8 @@ calc_evppi <- function(psa, evppi_ls <- list(df_evppi = df_evppi, metamodel_ls = l_mms) class(evppi_ls) <- c("evppi") + attr(evppi_ls, "currency") <- psa$currency + attr(evppi_ls, "outcome") <- outcome_input evppi_ls } @@ -138,7 +141,8 @@ calc_evppi <- function(psa, #' @param x object of class \code{evppi}, produced by function #' \code{\link{calc_evppi}} #' @param currency string with currency used in the cost-effectiveness analysis (CEA). -#' Default: $, but it could be any currency symbol or word (e.g., £, €, peso) +#' Default: the currency of the PSA the results were computed from (or $), but it could be any +#' currency symbol or word (e.g., £, €, peso) #' @param effect_units units of effectiveness. Default: QALY #' @inheritParams add_common_aes #' @keywords expected value of perfect information @@ -149,7 +153,7 @@ calc_evppi <- function(psa, #' @export plot.evppi <- function(x, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALY", n_y_ticks = 8, n_x_ticks = 20, @@ -159,13 +163,15 @@ plot.evppi <- function(x, ylim = NULL, ...) { WTP_thou <- EVPPI <- NULL + currency <- resolve_currency(currency, x) + v_units <- voi_units(x, currency, effect_units) x <- x[[1]] x$WTP_thou <- x$WTP / 1000 g <- ggplot(data = x, aes(x = WTP_thou, y = EVPPI)) + geom_line() + xlab(paste("Willingness to Pay (Thousand ", currency, "/", effect_units, ")", sep = "")) + - ylab(paste("EVPPI (", currency, ")", sep = "")) + ylab(paste("EVPPI (", v_units, ")", sep = "")) add_common_aes(g, txtsize, continuous = c("x", "y"), n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks, xbreaks = xbreaks, ybreaks = ybreaks, diff --git a/R/evsi.R b/R/evsi.R index ce0fdc1..e948448 100644 --- a/R/evsi.R +++ b/R/evsi.R @@ -32,6 +32,7 @@ calc_evsi <- function(psa, progress = TRUE) { # define parameter values and make sure they correspond to a valid option outcome <- match.arg(outcome) + outcome_input <- outcome # adjust outcome type outcome <- paste0(outcome, "_loss_voi") @@ -108,6 +109,8 @@ calc_evsi <- function(psa, } evsi_ls <- list(df_evsi = df_evsi, metamodel_ls = l_mms) class(evsi_ls) <- c("evsi") + attr(evsi_ls, "currency") <- psa$currency + attr(evsi_ls, "outcome") <- outcome_input evsi_ls } @@ -282,7 +285,8 @@ predict_matrix_tensor_smooth_ga <- function(object, #' @param x object of class \code{evsi}, produced by function #' \code{\link{calc_evsi}} #' @param currency string with currency used in the cost-effectiveness analysis (CEA). -#' Default: $, but it could be any currency symbol or word (e.g., £, €, peso) +#' Default: the currency of the PSA the results were computed from (or $), but it could be any +#' currency symbol or word (e.g., £, €, peso) #' @param effect_units units of effectiveness. Default: QALY #' @inheritParams add_common_aes #' @keywords expected value of sample information @@ -293,7 +297,7 @@ predict_matrix_tensor_smooth_ga <- function(object, #' @export plot.evsi <- function(x, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALY", n_y_ticks = 8, n_x_ticks = 20, @@ -305,6 +309,8 @@ plot.evsi <- function(x, ...) { # Select EVSI data.frame, discarding metamodel list EVSI <- WTP_thou <- NULL + currency <- resolve_currency(currency, x) + v_units <- voi_units(x, currency, effect_units) x <- x[[1]] x$WTP_thou <- x$WTP / 1000 col <- match.arg(col) @@ -332,7 +338,7 @@ plot.evsi <- function(x, g <- g + geom_line() + - ylab(paste("EVSI (", currency, ")", sep = "")) + ylab(paste("EVSI (", v_units, ")", sep = "")) add_common_aes(g, txtsize, continuous = c("x", "y"), n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks, xbreaks = xbreaks, ybreaks = ybreaks, diff --git a/R/exp_loss.R b/R/exp_loss.R index 71f9612..c5bc826 100644 --- a/R/exp_loss.R +++ b/R/exp_loss.R @@ -87,6 +87,7 @@ calc_exp_loss <- function(psa, wtp) { df_exp_loss_melt$Strategy <- factor(df_exp_loss_melt$Strategy, levels = v_strategies, ordered = TRUE) class(df_exp_loss_melt) <- c("exp_loss", "data.frame") + attr(df_exp_loss_melt, "currency") <- psa$currency df_exp_loss_melt } @@ -96,7 +97,8 @@ calc_exp_loss <- function(psa, wtp) { #' @param x object of class \code{exp_loss}, produced by function #' \code{\link{calc_exp_loss}} #' @param currency string with currency used in the cost-effectiveness analysis (CEA). -#' Default: $, but it could be any currency symbol or word (e.g., £, €, peso) +#' Default: the currency of the PSA the results were computed from (or $), but it could be any +#' currency symbol or word (e.g., £, €, peso) #' @param effect_units units of effectiveness. Default: QALY #' @param log_y take the base 10 log of the y axis #' @param frontier indicate the frontier (also the expected value of perfect information). @@ -117,7 +119,7 @@ plot.exp_loss <- function(x, points = TRUE, lsize = 1, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALY", n_y_ticks = 8, n_x_ticks = 20, @@ -128,6 +130,7 @@ plot.exp_loss <- function(x, col = c("access", "full", "bw"), ...) { On_Frontier <- NULL + currency <- resolve_currency(currency, x) wtp_name <- "WTP_thou" loss_name <- "Expected_Loss" strat_name <- "Strategy" diff --git a/R/icers.R b/R/icers.R index 98db64c..901f295 100644 --- a/R/icers.R +++ b/R/icers.R @@ -373,7 +373,8 @@ calculate_icers_psa <- function(psa, uncertainty = FALSE, ref_str = NULL, wtp = df_icers <- calculate_icers(cost = df_psa_sum$meanCost, effect = df_psa_sum$meanEffect, strategies = df_psa_sum$Strategy, - ref_str = ref_str, wtp = wtp, nhb = nhb) + ref_str = ref_str, wtp = wtp, nhb = nhb, + currency = psa$currency) if (uncertainty == TRUE) { # the joins and column selection below drop the icers class and attributes; keep them diff --git a/man/plot.ceac.Rd b/man/plot.ceac.Rd index ee09f84..ff0e269 100644 --- a/man/plot.ceac.Rd +++ b/man/plot.ceac.Rd @@ -8,7 +8,7 @@ x, frontier = TRUE, points = TRUE, - currency = "$", + currency = NULL, min_prob = 0, txtsize = 12, n_x_ticks = 10, @@ -18,6 +18,7 @@ ylim = NULL, xlim = c(0, NA), col = c("access", "full", "bw"), + effect_units = "QALY", ... ) } @@ -29,7 +30,8 @@ \item{points}{whether to plot points (TRUE) or not (FALSE)} \item{currency}{string with currency used in the cost-effectiveness analysis (CEA). -Defaults to \code{$}, but can be any currency symbol or word (e.g., £, €, peso)} +Defaults to the currency of the PSA the CEAC was computed from (or \code{$}), but can be any +currency symbol or word (e.g., £, €, peso).} \item{min_prob}{minimum probability to show strategy in plot. For example, if the min_prob is 0.05, only strategies that ever @@ -54,6 +56,8 @@ will override \code{n_y_ticks} if provided.} \item{col}{either none, full color, accessible colors, or black and white} +\item{effect_units}{units of effectiveness, used in the x-axis label. Default: QALY} + \item{...}{further arguments to plot. This is not used by \code{dampack} but required for generic consistency.} } diff --git a/man/plot.evpi.Rd b/man/plot.evpi.Rd index bb878a6..1978b0f 100644 --- a/man/plot.evpi.Rd +++ b/man/plot.evpi.Rd @@ -7,7 +7,7 @@ \method{plot}{evpi}( x, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALY", n_y_ticks = 8, n_x_ticks = 20, @@ -25,7 +25,8 @@ \item{txtsize}{base text size} \item{currency}{string with currency used in the cost-effectiveness analysis (CEA). -Default: $, but it could be any currency symbol or word (e.g., £, €, peso)} +Default: the currency of the PSA the results were computed from (or $), but it could be any +currency symbol or word (e.g., £, €, peso)} \item{effect_units}{units of effectiveness. Default: QALY} diff --git a/man/plot.evppi.Rd b/man/plot.evppi.Rd index 0174fd5..519e9df 100644 --- a/man/plot.evppi.Rd +++ b/man/plot.evppi.Rd @@ -7,7 +7,7 @@ \method{plot}{evppi}( x, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALY", n_y_ticks = 8, n_x_ticks = 20, @@ -25,7 +25,8 @@ \item{txtsize}{base text size} \item{currency}{string with currency used in the cost-effectiveness analysis (CEA). -Default: $, but it could be any currency symbol or word (e.g., £, €, peso)} +Default: the currency of the PSA the results were computed from (or $), but it could be any +currency symbol or word (e.g., £, €, peso)} \item{effect_units}{units of effectiveness. Default: QALY} diff --git a/man/plot.evsi.Rd b/man/plot.evsi.Rd index fdc8186..0c9e858 100644 --- a/man/plot.evsi.Rd +++ b/man/plot.evsi.Rd @@ -7,7 +7,7 @@ \method{plot}{evsi}( x, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALY", n_y_ticks = 8, n_x_ticks = 20, @@ -26,7 +26,8 @@ \item{txtsize}{base text size} \item{currency}{string with currency used in the cost-effectiveness analysis (CEA). -Default: $, but it could be any currency symbol or word (e.g., £, €, peso)} +Default: the currency of the PSA the results were computed from (or $), but it could be any +currency symbol or word (e.g., £, €, peso)} \item{effect_units}{units of effectiveness. Default: QALY} diff --git a/man/plot.exp_loss.Rd b/man/plot.exp_loss.Rd index 5e4322e..0d46626 100644 --- a/man/plot.exp_loss.Rd +++ b/man/plot.exp_loss.Rd @@ -11,7 +11,7 @@ points = TRUE, lsize = 1, txtsize = 12, - currency = "$", + currency = NULL, effect_units = "QALY", n_y_ticks = 8, n_x_ticks = 20, @@ -39,7 +39,8 @@ To only plot the EVPI see \code{\link{calc_evpi}}.} \item{txtsize}{base text size} \item{currency}{string with currency used in the cost-effectiveness analysis (CEA). -Default: $, but it could be any currency symbol or word (e.g., £, €, peso)} +Default: the currency of the PSA the results were computed from (or $), but it could be any +currency symbol or word (e.g., £, €, peso)} \item{effect_units}{units of effectiveness. Default: QALY} diff --git a/man/resolve_currency.Rd b/man/resolve_currency.Rd new file mode 100644 index 0000000..5782d21 --- /dev/null +++ b/man/resolve_currency.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/add_common_aes.R +\name{resolve_currency} +\alias{resolve_currency} +\title{Currency to use for labels} +\usage{ +resolve_currency(currency, x) +} +\arguments{ +\item{currency}{currency given by the user, or \code{NULL}.} + +\item{x}{a result object that may carry a \code{"currency"} attribute.} +} +\value{ +\code{currency} if given, otherwise the currency stored on \code{x}, otherwise \code{"$"}. +} +\description{ +Currency to use for labels +} +\keyword{internal} diff --git a/man/voi_units.Rd b/man/voi_units.Rd new file mode 100644 index 0000000..c865f77 --- /dev/null +++ b/man/voi_units.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/add_common_aes.R +\name{voi_units} +\alias{voi_units} +\title{Units of a value-of-information result} +\usage{ +voi_units(x, currency, effect_units) +} +\arguments{ +\item{x}{an \code{evppi} or \code{evsi} object.} + +\item{currency}{currency label.} + +\item{effect_units}{units of effectiveness.} +} +\value{ +\code{effect_units} if \code{x} was computed with \code{outcome = "nhb"}, else \code{currency}. +} +\description{ +EVPPI and EVSI computed from net health benefit are in health units; from net monetary +benefit, in currency. +} +\keyword{internal} diff --git a/tests/testthat/test_calculate_icers.R b/tests/testthat/test_calculate_icers.R index fe9e6df..3aa5e94 100644 --- a/tests/testthat/test_calculate_icers.R +++ b/tests/testthat/test_calculate_icers.R @@ -91,7 +91,8 @@ test_that("psa icers returns icers df corresponding to means", { psa_sum <- summary(psa_big) exp_icers <- calculate_icers(cost = psa_sum$meanCost, effect = psa_sum$meanEffect, - strategies = psa_sum$Strategy) + strategies = psa_sum$Strategy, + currency = psa_big$currency) expect_equal(psa_icers, exp_icers) }) diff --git a/tests/testthat/test_currency.R b/tests/testthat/test_currency.R new file mode 100644 index 0000000..65cf20f --- /dev/null +++ b/tests/testthat/test_currency.R @@ -0,0 +1,54 @@ +context("the currency of a psa object carries through to results, plots, and tables (#203)") + +cancer_psa_data <- dampack::cancer_psa_data +psa_eur <- make_psa_obj(cancer_psa_data$cost, cancer_psa_data$effectiveness, + cancer_psa_data$parameters, cancer_psa_data$strategies, + currency = "€") +psa_usd <- make_psa_obj(cancer_psa_data$cost, cancer_psa_data$effectiveness, + cancer_psa_data$parameters, cancer_psa_data$strategies) +v_wtp <- seq(10000, 100000, by = 30000) +eur <- "€" + +test_that("ceac() and calc_exp_loss() keep the currency and use it in their plots", { + df_ceac <- ceac(v_wtp, psa_eur) + expect_identical(attr(df_ceac, "currency"), eur) + expect_match(plot(df_ceac)$labels$x, eur, fixed = TRUE) + expect_match(plot(df_ceac, currency = "£")$labels$x, "£", fixed = TRUE) + expect_match(plot(df_ceac, effect_units = "LY")$labels$x, "/ LY)", fixed = TRUE) + + df_elc <- calc_exp_loss(psa_eur, v_wtp) + expect_identical(attr(df_elc, "currency"), eur) + expect_equal(plot(df_elc)$labels$y, paste0("Expected Loss (", eur, ")")) +}) + +test_that("EVPI, EVPPI, and EVSI plots use the currency or the health units of the outcome", { + df_evpi <- calc_evpi(psa_eur, v_wtp) + expect_identical(attr(df_evpi, "currency"), eur) + expect_equal(plot(df_evpi)$labels$y, paste0("EVPI (", eur, ")")) + + evppi_nmb <- calc_evppi(psa_eur, v_wtp, params = "pFailChemo", outcome = "nmb", progress = FALSE) + expect_equal(plot(evppi_nmb)$labels$y, paste0("EVPPI (", eur, ")")) + evppi_nhb <- calc_evppi(psa_eur, v_wtp, params = "pFailChemo", outcome = "nhb", progress = FALSE) + expect_equal(plot(evppi_nhb)$labels$y, "EVPPI (QALY)") + + # calc_evsi() defaults to outcome = "nhb", whose EVSI is in health units, not currency + evsi_nhb <- calc_evsi(psa_eur, v_wtp, params = "pFailChemo", n = 100, n0 = 10, progress = FALSE) + expect_equal(plot(evsi_nhb)$labels$y, "EVSI (QALY)") + evsi_nmb <- calc_evsi(psa_eur, v_wtp, params = "pFailChemo", n = 100, n0 = 10, + outcome = "nmb", progress = FALSE) + expect_equal(plot(evsi_nmb)$labels$y, paste0("EVSI (", eur, ")")) +}) + +test_that("calculate_icers_psa() keeps the currency for print and plot", { + x <- calculate_icers_psa(psa_eur) + expect_identical(attr(x, "currency"), eur) + expect_true(any(grepl(paste0("Costs (", eur, ")"), capture.output(print(x)), fixed = TRUE))) + expect_equal(plot(x)$labels$y, paste0("Cost (", eur, ")")) + x_unc <- calculate_icers_psa(psa_eur, uncertainty = TRUE) + expect_identical(attr(x_unc, "currency"), eur) +}) + +test_that("a dollar psa object still gives dollar labels", { + expect_match(plot(ceac(v_wtp, psa_usd))$labels$x, "$", fixed = TRUE) + expect_equal(plot(calc_evpi(psa_usd, v_wtp))$labels$y, "EVPI ($)") +}) diff --git a/tests/testthat/test_psa_reference.R b/tests/testthat/test_psa_reference.R index 79e0f2b..1df2caf 100644 --- a/tests/testthat/test_psa_reference.R +++ b/tests/testthat/test_psa_reference.R @@ -46,7 +46,7 @@ psa_big <- make_psa_obj(cancer_psa_data$cost, cancer_psa_data$effectiveness, test_that("calculate_icers_psa() passes ref_str, wtp, and nhb to calculate_icers()", { s <- summary(psa_big) expected <- calculate_icers(s$meanCost, s$meanEffect, s$Strategy, - ref_str = "Surgery", wtp = 50000, nhb = TRUE) + ref_str = "Surgery", wtp = 50000, nhb = TRUE, currency = psa_big$currency) obtained <- calculate_icers_psa(psa_big, ref_str = "Surgery", wtp = 50000, nhb = TRUE) expect_equal(obtained, expected) }) @@ -65,7 +65,7 @@ test_that("calculate_icers_psa(uncertainty = TRUE) adds intervals for the refere expect_true(is.na(r_ref$Lower_95_Inc_Cost_ref)) # the frontier-based columns and their existing intervals are unchanged x0 <- calculate_icers_psa(psa_big, uncertainty = TRUE) - expect_equal(as.data.frame(x)[, names(x0)], as.data.frame(x0)) + expect_equal(as.data.frame(x)[, names(x0)], as.data.frame(x0)[, names(x0)]) }) test_that("print.icers() keeps reference intervals out of the sequential view", { From 308850ff157738c8e414da8b600437fcb521a3ea Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Fri, 13 Nov 2026 14:57:33 -0800 Subject: [PATCH 05/10] Address review of #227: reference-first print order, Inc_NMB_ref naming, wtp without ref_str in plot.psa - print.icers(ref = "reference") lists the reference first and the other strategies by increasing cost; "sequential" and "both" keep the frontier order. - Rename iNMB_ref/iNHB_ref to Inc_NMB_ref/Inc_NHB_ref, matching Inc_Cost_ref, Inc_Effect_ref and summary.psa()'s meanIncNMB. Print headers say "Incremental NMB/NHB". - plot.psa(wtp = ) no longer requires ref_str: without one, the line goes through the mean of the least costly strategy, as plot.icers() already did. - Comment add_reference_and_nmb(), add_reference_intervals(), the global-variable declarations, and the everything() in calculate_icers_psa(). --- NEWS.md | 4 +- R/icers.R | 53 +++++++++++++++++++++------ R/psa.R | 22 ++++++++--- man/calculate_icers.Rd | 4 +- man/calculate_icers_psa.Rd | 2 +- man/plot.psa.Rd | 6 ++- man/print.icers.Rd | 4 +- tests/testthat/test_icers_reference.R | 21 +++++++++-- tests/testthat/test_psa_reference.R | 2 +- tests/testthat/test_reference_plots.R | 12 +++++- 10 files changed, 99 insertions(+), 31 deletions(-) diff --git a/NEWS.md b/NEWS.md index e50e381..d298dcb 100644 --- a/NEWS.md +++ b/NEWS.md @@ -5,9 +5,9 @@ - The currency of a `psa` object now carries through to its analyses: `ceac()`, `calc_exp_loss()`, `calc_evpi()`, `calc_evppi()`, `calc_evsi()`, and `calculate_icers_psa()` keep it, and their `plot()` and `print()` methods use it unless `currency` is given. `plot.ceac()` gains `effect_units` (#203). - `summary.psa()` gains `ref_str` and `wtp`. With a reference strategy it adds the mean incremental cost and effect and the proportion of PSA samples in each quadrant of the incremental cost-effectiveness plane (`propNE`, `propSE`, `propSW`, `propNW`); with `wtp` it adds the mean NMB and, with a reference, `meanIncNMB` and the proportion of samples that are cost-effective compared with the reference (`propCostEffective`) (#209, #202). - `calculate_icers_psa()` gains `ref_str`, `wtp`, and `nhb`. With `uncertainty = TRUE` and a reference strategy, it adds 95% intervals for the differences from the reference, computed sample by sample (#209). -- `plot.icers()` gains `ref_str`, which plots the incremental cost-effectiveness plane with the reference strategy at the origin, and `wtp`, which draws a willingness-to-pay line. `plot.psa()` gains `wtp` for the same line on its incremental plane. `plot.icers()` uses the currency stored by `calculate_icers()` (#209, #202). +- `plot.icers()` gains `ref_str`, which plots the incremental cost-effectiveness plane with the reference strategy at the origin, and `wtp`, which draws a willingness-to-pay line. `plot.psa()` gains `wtp` for the same line, drawn through the reference strategy or, without one, through the least costly strategy. `plot.icers()` uses the currency stored by `calculate_icers()` (#209, #202). - `calculate_icers()` can compare every strategy with a user-selected reference strategy: with `ref_str = "Standard of care"`, it adds `Inc_Cost_ref`, `Inc_Effect_ref`, `ICER_ref`, and `Status_ref` ("Reference", "Dominant", "Dominated", "More costly, more effective", "Less costly, less effective", or "Equivalent"). The frontier-based results are unchanged, and without `ref_str` no columns are added (#209). -- `calculate_icers()` gains `wtp`, which adds the net monetary benefit (`NMB`, and `iNMB_ref` with a reference strategy), and `nhb = TRUE`, which also adds the net health benefit (`NHB`, `iNHB_ref`) (#200). +- `calculate_icers()` gains `wtp`, which adds the net monetary benefit (`NMB`, and `Inc_NMB_ref` with a reference strategy), and `nhb = TRUE`, which also adds the net health benefit (`NHB`, `Inc_NHB_ref`) (#200). - `calculate_icers()` gains `currency`, used by `print.icers()`. `print.icers()` gains `ref`: `"sequential"` (the default) prints the usual table, and `"reference"` or `"both"` print the comparison with the reference strategy (#209). - `print.icers()` prints a formatted ICER table, with options for the currency symbol and the number of digits (#184, #171). - `plot.psa()` gains a `ref_str` argument that plots the PSA on the incremental cost-effectiveness plane relative to a chosen reference strategy (#188). diff --git a/R/icers.R b/R/icers.R index 901f295..3aece10 100644 --- a/R/icers.R +++ b/R/icers.R @@ -39,8 +39,8 @@ #' for dominant, dominated, and equivalent strategies. #' #' If \code{wtp} is given, \code{NMB} (\code{wtp * Effect - Cost}) is added, and with -#' \code{ref_str} also \code{iNMB_ref}, the NMB minus that of the reference. With -#' \code{nhb = TRUE}, \code{NHB} (\code{Effect - Cost / wtp}) and \code{iNHB_ref} are added too. +#' \code{ref_str} also \code{Inc_NMB_ref}, the NMB minus that of the reference. With +#' \code{nhb = TRUE}, \code{NHB} (\code{Effect - Cost / wtp}) and \code{Inc_NHB_ref} are added too. #' #' @seealso \code{\link{plot.icers}} #' @@ -100,6 +100,8 @@ calculate_icers <- function(cost, effect, strategies, ref_str = NULL, wtp = NULL ref_str <- check_ref_str(ref_str, as.character(strategies)) check_wtp_nhb(wtp, nhb) + # column names used unquoted in the dplyr code below; declaring them avoids the + # R CMD check note "no visible binding for global variable" Cost <- Effect <- Status <- Strategy <- Inc_Cost <- Inc_Effect <- ICER <- NULL # coerce to character, in case they are provided as numeric @@ -288,31 +290,41 @@ status_vs_reference <- function(v_inc_cost, v_inc_effect) { #' @keywords internal add_reference_and_nmb <- function(df_icers, ref_str, wtp, nhb, currency) { if (!is.null(ref_str)) { + # row of the reference strategy; check_ref_str() has already confirmed it exists i_ref <- match(ref_str, df_icers$Strategy) + # differences of every strategy from the reference (the reference's own are 0) v_inc_cost <- df_icers$Cost - df_icers$Cost[i_ref] v_inc_effect <- df_icers$Effect - df_icers$Effect[i_ref] + # classify each strategy by its quadrant of the incremental CE plane v_status <- status_vs_reference(v_inc_cost, v_inc_effect) + # the reference has no comparison with itself: label it and blank its differences v_status[i_ref] <- "Reference" v_inc_cost[i_ref] <- NA_real_ v_inc_effect[i_ref] <- NA_real_ + # a ratio is only meaningful when cost and effect move in the same direction (NE and SW + # quadrants); for dominant, dominated, and equivalent strategies ICER_ref stays NA v_has_ratio <- v_status %in% c("More costly, more effective", "Less costly, less effective") df_icers$Inc_Cost_ref <- v_inc_cost df_icers$Inc_Effect_ref <- v_inc_effect df_icers$ICER_ref <- ifelse(v_has_ratio, v_inc_cost / v_inc_effect, NA_real_) df_icers$Status_ref <- v_status + # print.icers() and plot.icers() read the reference from this attribute attr(df_icers, "ref_str") <- ref_str } if (!is.null(wtp)) { + # net monetary benefit of each strategy at the given threshold df_icers$NMB <- wtp * df_icers$Effect - df_icers$Cost if (!is.null(ref_str)) { - df_icers$iNMB_ref <- df_icers$NMB - df_icers$NMB[i_ref] - df_icers$iNMB_ref[i_ref] <- NA_real_ + # incremental NMB versus the reference; positive means cost-effective versus the reference + df_icers$Inc_NMB_ref <- df_icers$NMB - df_icers$NMB[i_ref] + df_icers$Inc_NMB_ref[i_ref] <- NA_real_ } if (nhb) { + # net health benefit: the same comparison expressed in units of effect df_icers$NHB <- df_icers$Effect - df_icers$Cost / wtp if (!is.null(ref_str)) { - df_icers$iNHB_ref <- df_icers$NHB - df_icers$NHB[i_ref] - df_icers$iNHB_ref[i_ref] <- NA_real_ + df_icers$Inc_NHB_ref <- df_icers$NHB - df_icers$NHB[i_ref] + df_icers$Inc_NHB_ref[i_ref] <- NA_real_ } } attr(df_icers, "wtp") <- wtp @@ -353,7 +365,7 @@ add_reference_and_nmb <- function(df_icers, ref_str, wtp, nhb, currency) { #' described in \code{\link{calculate_icers}} are added. With \code{uncertainty = TRUE} and #' \code{ref_str}, the 2.5th and 97.5th quantiles of the sample-by-sample differences from the reference #' are also given for \code{Inc_Cost_ref}, \code{Inc_Effect_ref}, and (with \code{wtp}) -#' \code{iNMB_ref}, in columns such as \code{Lower_95_Inc_Cost_ref} and \code{Upper_95_Inc_Cost_ref}. +#' \code{Inc_NMB_ref}, in columns such as \code{Lower_95_Inc_Cost_ref} and \code{Upper_95_Inc_Cost_ref}. #' @seealso \code{\link{plot.icers}} #' @seealso \code{\link{calculate_icers}} #' @importFrom tidyr pivot_longer @@ -366,6 +378,8 @@ calculate_icers_psa <- function(psa, uncertainty = FALSE, ref_str = NULL, wtp = # Calculate mean outcome values df_psa_sum <- summary(psa) + # column names used unquoted in the dplyr code below; declaring them avoids the + # R CMD check note "no visible binding for global variable" Cost <- Effect <- Status <- Strategy <- Inc_Cost <- Inc_Effect <- ICER <- value <- Lower_95_Cost <- Upper_95_Cost <- Lower_95_Effect <- Upper_95_Effect <- NULL @@ -402,6 +416,8 @@ calculate_icers_psa <- function(psa, uncertainty = FALSE, ref_str = NULL, wtp = df_icers <- df_icers %>% left_join(df_cost_bounds, by = "Strategy") %>% left_join(df_effect_bounds, by = "Strategy") %>% + # put each interval next to its estimate; everything() keeps the remaining columns + # (the reference and net-benefit columns), which select() would otherwise drop select(Strategy, Cost, Lower_95_Cost, Upper_95_Cost, Effect, Lower_95_Effect, Upper_95_Effect, Inc_Cost, Inc_Effect, ICER, Status, everything()) @@ -429,18 +445,24 @@ calculate_icers_psa <- function(psa, uncertainty = FALSE, ref_str = NULL, wtp = #' @return \code{df_icers} with the interval columns added. #' @keywords internal add_reference_intervals <- function(df_icers, psa, ref_str, wtp) { + # sample-by-sample differences from the reference: one row per PSA sample, one column per + # strategy (subtracting a vector from a matrix recycles it down each column) m_inc_cost <- as.matrix(psa$cost) - psa$cost[[ref_str]] m_inc_effect <- as.matrix(psa$effectiveness) - psa$effectiveness[[ref_str]] + # one matrix of differences per point-estimate column that gets an interval l_inc <- list(Inc_Cost_ref = m_inc_cost, Inc_Effect_ref = m_inc_effect) if (!is.null(wtp)) { - l_inc$iNMB_ref <- wtp * m_inc_effect - m_inc_cost + l_inc$Inc_NMB_ref <- wtp * m_inc_effect - m_inc_cost } v_strat <- df_icers$Strategy + # running column order, so each interval lands right after its point estimate v_cols <- names(df_icers) for (col in names(l_inc)) { + # reorder the matrix columns to match the rows of df_icers (frontier order) m_inc <- l_inc[[col]][, v_strat, drop = FALSE] v_lower <- unname(apply(m_inc, 2, quantile, probs = 0.025, names = FALSE)) v_upper <- unname(apply(m_inc, 2, quantile, probs = 0.975, names = FALSE)) + # the reference's differences are all 0, so its interval is reported as NA v_lower[v_strat == ref_str] <- NA_real_ v_upper[v_strat == ref_str] <- NA_real_ df_icers[[paste0("Lower_95_", col)]] <- v_lower @@ -659,7 +681,9 @@ plot.icers <- function(x, #' By default, prints the sequential cost-effectiveness table: each strategy on the frontier is #' compared with the previous one. If the \code{icers} object was created with a reference #' strategy (\code{ref_str} in \code{\link{calculate_icers}}), \code{ref = "reference"} shows the -#' comparison of every strategy with the reference instead, and \code{ref = "both"} shows both. +#' comparison of every strategy with the reference instead, listing the reference first and the +#' other strategies by increasing cost. \code{ref = "both"} shows both comparisons, in the +#' frontier order of the sequential table. #' #' @param x Object of class \code{icers} #' @param currency string. with currency used in the cost-effectiveness analysis (CEA). @@ -714,6 +738,13 @@ print.icers <- function(x, df_table_cea <- x class(df_table_cea) <- "data.frame" df_table_cea <- df_table_cea[, setdiff(names(df_table_cea), v_drop), drop = FALSE] + # the reference view lists the reference first, then the other strategies by cost; the + # sequential and combined views keep the frontier order, in which the sequential ICERs are read + if (ref == "reference") { + v_order <- order(df_table_cea$Strategy != ref_str, df_table_cea$Cost) + df_table_cea <- df_table_cea[v_order, , drop = FALSE] + rownames(df_table_cea) <- NULL + } # display digits and header for each known column vs <- paste0(" vs ", ref_str) @@ -728,9 +759,9 @@ print.icers <- function(x, ICER_ref = list(dig_icer, paste0("ICER", vs, " (", currency, "/QALY)")), Status_ref = list(NA, paste0("Status", vs)), NMB = list(dig_cost, paste0("NMB (", currency, ")")), - iNMB_ref = list(dig_cost, paste0("iNMB", vs, " (", currency, ")")), + Inc_NMB_ref = list(dig_cost, paste0("Incremental NMB", vs, " (", currency, ")")), NHB = list(dig_eff, "NHB (QALYs)"), - iNHB_ref = list(dig_eff, paste0("iNHB", vs, " (QALYs)")) + Inc_NHB_ref = list(dig_eff, paste0("Incremental NHB", vs, " (QALYs)")) ) for (col in intersect(names(l_format), names(df_table_cea))) { if (!is.na(l_format[[col]][[1]])) { diff --git a/R/psa.R b/R/psa.R index f2def64..2267f72 100644 --- a/R/psa.R +++ b/R/psa.R @@ -184,8 +184,10 @@ summary.psa <- function(object, calc_sds = FALSE, ref_str = NULL, wtp = NULL, .. #' @param ref_caption Add the reference strategy (and the WTP threshold, if given) as a caption. #' Defaults to TRUE #' @param wtp a willingness-to-pay threshold. If given, a dotted line with slope \code{wtp} is -#' drawn through the origin of the incremental cost-effectiveness plane; samples below the line are -#' cost-effective compared with the reference strategy at this threshold. Requires \code{ref_str}. +#' drawn through the reference strategy, which with \code{ref_str} is the origin of the incremental +#' cost-effectiveness plane. Without \code{ref_str}, the line goes through the mean cost and effect +#' of the least costly strategy, as in \code{\link{plot.icers}}. Samples below the line are +#' cost-effective compared with that strategy at this threshold. #' @inheritParams add_common_aes #' #' @importFrom ellipse ellipse @@ -216,10 +218,6 @@ plot.psa <- function(x, v_strategies <- x$strategies currency <- x$currency ref_str <- check_ref_str(ref_str, v_strategies) - if (!is.null(wtp) && is.null(ref_str)) { - stop("`wtp` draws a willingness-to-pay line on the incremental cost-effectiveness plane, ", - "so it needs `ref_str`.", call. = FALSE) - } check_wtp_nhb(wtp, nhb = FALSE) if (is.null(ref_str)) { @@ -279,6 +277,18 @@ plot.psa <- function(x, linewidth = 1, linetype = 2, alpha = 1) } + # WTP line through the mean of the least costly strategy, matching plot.icers() + if (!is.null(wtp)) { + v_mean_cost <- colMeans(df_cost_wide) + i_anchor <- which.min(v_mean_cost) + intercept <- v_mean_cost[[i_anchor]] - wtp * mean(df_effectiveness_wide[[i_anchor]]) + psa_plot <- psa_plot + + geom_abline(intercept = intercept, slope = wtp, linetype = "dotted", color = "grey30") + if (ref_caption) { + psa_plot <- psa_plot + labs(caption = wtp_caption(wtp, currency)) + } + } + # add common theme col <- match.arg(col) add_common_aes(psa_plot, txtsize, col = col, col_aes = c("color", "fill"), diff --git a/man/calculate_icers.Rd b/man/calculate_icers.Rd index 0c4132b..83a4a8a 100644 --- a/man/calculate_icers.Rd +++ b/man/calculate_icers.Rd @@ -50,8 +50,8 @@ and no more effective), \code{"More costly, more effective"}, for dominant, dominated, and equivalent strategies. If \code{wtp} is given, \code{NMB} (\code{wtp * Effect - Cost}) is added, and with -\code{ref_str} also \code{iNMB_ref}, the NMB minus that of the reference. With -\code{nhb = TRUE}, \code{NHB} (\code{Effect - Cost / wtp}) and \code{iNHB_ref} are added too. +\code{ref_str} also \code{Inc_NMB_ref}, the NMB minus that of the reference. With +\code{nhb = TRUE}, \code{NHB} (\code{Effect - Cost / wtp}) and \code{Inc_NHB_ref} are added too. } \description{ This function takes in strategies and their associated cost and effect, assigns them diff --git a/man/calculate_icers_psa.Rd b/man/calculate_icers_psa.Rd index e5cfc61..3766cea 100644 --- a/man/calculate_icers_psa.Rd +++ b/man/calculate_icers_psa.Rd @@ -39,7 +39,7 @@ With \code{ref_str}, \code{wtp}, or \code{nhb}, the reference-strategy and net-b described in \code{\link{calculate_icers}} are added. With \code{uncertainty = TRUE} and \code{ref_str}, the 2.5th and 97.5th quantiles of the sample-by-sample differences from the reference are also given for \code{Inc_Cost_ref}, \code{Inc_Effect_ref}, and (with \code{wtp}) -\code{iNMB_ref}, in columns such as \code{Lower_95_Inc_Cost_ref} and \code{Upper_95_Inc_Cost_ref}. +\code{Inc_NMB_ref}, in columns such as \code{Lower_95_Inc_Cost_ref} and \code{Upper_95_Inc_Cost_ref}. } \description{ The mean costs and QALYs for each strategy in a PSA are used diff --git a/man/plot.psa.Rd b/man/plot.psa.Rd index 954ba5a..ac144a5 100644 --- a/man/plot.psa.Rd +++ b/man/plot.psa.Rd @@ -61,8 +61,10 @@ will override \code{n_y_ticks} if provided.} Defaults to TRUE} \item{wtp}{a willingness-to-pay threshold. If given, a dotted line with slope \code{wtp} is -drawn through the origin of the incremental cost-effectiveness plane; samples below the line are -cost-effective compared with the reference strategy at this threshold. Requires \code{ref_str}.} +drawn through the reference strategy, which with \code{ref_str} is the origin of the incremental +cost-effectiveness plane. Without \code{ref_str}, the line goes through the mean cost and effect +of the least costly strategy, as in \code{\link{plot.icers}}. Samples below the line are +cost-effective compared with that strategy at this threshold.} \item{...}{further arguments to plot. This is not used by \code{dampack} but required for generic consistency.} diff --git a/man/print.icers.Rd b/man/print.icers.Rd index 8467e45..558f9aa 100644 --- a/man/print.icers.Rd +++ b/man/print.icers.Rd @@ -38,5 +38,7 @@ a dataframe object - formatted CEA table By default, prints the sequential cost-effectiveness table: each strategy on the frontier is compared with the previous one. If the \code{icers} object was created with a reference strategy (\code{ref_str} in \code{\link{calculate_icers}}), \code{ref = "reference"} shows the -comparison of every strategy with the reference instead, and \code{ref = "both"} shows both. +comparison of every strategy with the reference instead, listing the reference first and the +other strategies by increasing cost. \code{ref = "both"} shows both comparisons, in the +frontier order of the sequential table. } diff --git a/tests/testthat/test_icers_reference.R b/tests/testthat/test_icers_reference.R index 0d410dc..e534651 100644 --- a/tests/testthat/test_icers_reference.R +++ b/tests/testthat/test_icers_reference.R @@ -63,17 +63,17 @@ test_that("a dominated or the most expensive strategy can be the reference", { test_that("NMB is added by default with wtp, NHB only on request", { x <- toy_icers(wtp = 150) expect_equal(x$NMB, 150 * x$Effect - x$Cost) - expect_false(any(c("NHB", "iNMB_ref", "iNHB_ref") %in% names(x))) + expect_false(any(c("NHB", "Inc_NMB_ref", "Inc_NHB_ref") %in% names(x))) expect_identical(attr(x, "wtp"), 150) y <- toy_icers(ref_str = "Ref", wtp = 150) - expect_equal(row_of(y, "More")$iNMB_ref, (150 * 2 - 200) - (150 * 1 - 100)) - expect_true(is.na(row_of(y, "Ref")$iNMB_ref)) + expect_equal(row_of(y, "More")$Inc_NMB_ref, (150 * 2 - 200) - (150 * 1 - 100)) + expect_true(is.na(row_of(y, "Ref")$Inc_NMB_ref)) expect_false("NHB" %in% names(y)) z <- toy_icers(ref_str = "Ref", wtp = 150, nhb = TRUE) expect_equal(z$NHB, z$Effect - z$Cost / 150) - expect_equal(row_of(z, "Cheaper")$iNHB_ref, (1.5 - 50 / 150) - (1 - 100 / 150)) + expect_equal(row_of(z, "Cheaper")$Inc_NHB_ref, (1.5 - 50 / 150) - (1 - 100 / 150)) }) test_that("hund_strat: reference columns equal the difference from the reference", { @@ -121,3 +121,16 @@ test_that("print.icers shows the sequential table by default and the reference v expect_error(print(toy_icers(), ref = "reference"), "no reference strategy") }) + +test_that("print(ref = \"reference\") lists the reference first, then by cost", { + data(hund_strat) + x <- calculate_icers(hund_strat$Cost, hund_strat$QALYs, hund_strat$Strategy, ref_str = "1") + expect_true(which(x$Strategy == "1") > 1) + out <- utils::capture.output(tbl <- print(x, ref = "reference")) + expect_equal(tbl$Strategy[1], "1") + v_rest <- hund_strat[hund_strat$Strategy != 1, ] + expect_equal(tbl$Strategy[-1], as.character(v_rest$Strategy[order(v_rest$Cost)])) + # the sequential and combined views keep the frontier order of the object + out <- utils::capture.output(tbl_both <- print(x, ref = "both")) + expect_equal(tbl_both$Strategy, x$Strategy) +}) diff --git a/tests/testthat/test_psa_reference.R b/tests/testthat/test_psa_reference.R index 1df2caf..596fbc3 100644 --- a/tests/testthat/test_psa_reference.R +++ b/tests/testthat/test_psa_reference.R @@ -60,7 +60,7 @@ test_that("calculate_icers_psa(uncertainty = TRUE) adds intervals for the refere expect_equal(r$Lower_95_Inc_Cost_ref, unname(quantile(d_cost, 0.025))) expect_equal(r$Upper_95_Inc_Cost_ref, unname(quantile(d_cost, 0.975))) expect_equal(r$Lower_95_Inc_Effect_ref, unname(quantile(d_eff, 0.025))) - expect_equal(r$Upper_95_iNMB_ref, unname(quantile(50000 * d_eff - d_cost, 0.975))) + expect_equal(r$Upper_95_Inc_NMB_ref, unname(quantile(50000 * d_eff - d_cost, 0.975))) r_ref <- x[x$Strategy == "Surgery", ] expect_true(is.na(r_ref$Lower_95_Inc_Cost_ref)) # the frontier-based columns and their existing intervals are unchanged diff --git a/tests/testthat/test_reference_plots.R b/tests/testthat/test_reference_plots.R index 8612bf7..cd7ca2a 100644 --- a/tests/testthat/test_reference_plots.R +++ b/tests/testthat/test_reference_plots.R @@ -73,7 +73,17 @@ test_that("plot.psa(wtp = ) draws the WTP line on the incremental plane", { expect_length(i, 1) expect_equal(ggplot2::layer_data(p, i)$slope, 2000) expect_match(p$labels$caption, "WTP = $2,000/QALY", fixed = TRUE) - expect_error(plot(psa_2, wtp = 2000), "needs `ref_str`") expect_error(plot(psa_2, ref_str = "Nope"), "must be one of the strategies") expect_length(abline_layers(plot(psa_2)), 0) }) + +test_that("plot.psa(wtp = ) without ref_str draws the line through the least costly strategy", { + p <- plot(psa_2, wtp = 2000) + i <- abline_layers(p) + expect_length(i, 1) + d <- ggplot2::layer_data(p, i) + # A ("Standard of care") has the lower mean cost, so the line passes through its means + expect_equal(d$slope, 2000) + expect_equal(d$intercept, mean(df_cost2$A) - 2000 * mean(df_eff2$A)) + expect_match(p$labels$caption, "WTP = $2,000/QALY", fixed = TRUE) +}) From ae98e8c98884219b795b97596797c9466d249d35 Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Fri, 13 Nov 2026 15:35:41 -0800 Subject: [PATCH 06/10] Merge-with-main fixes: identical plot.icers data with or without uncertainty; drop context() for testthat 3e - plot.icers() now always reduces x to its seven plot columns as a plain data frame. dplyr::select() had dropped the stored currency attribute only when uncertainty bounds were present, so the two plots differed under testthat's edition-3 comparison. - Replace context() in the four test files added by this PR (deprecated in edition 3). --- R/icers.R | 14 ++++++-------- tests/testthat/test_currency.R | 2 +- tests/testthat/test_icers_reference.R | 2 +- tests/testthat/test_psa_reference.R | 2 +- tests/testthat/test_reference_plots.R | 2 +- 5 files changed, 10 insertions(+), 12 deletions(-) diff --git a/R/icers.R b/R/icers.R index 3aece10..55780b8 100644 --- a/R/icers.R +++ b/R/icers.R @@ -553,20 +553,18 @@ plot.icers <- function(x, ref_axis = TRUE, ref_caption = TRUE, ...) { - Cost <- Effect <- Status <- Strategy <- Inc_Cost <- Inc_Effect <- ICER <- NULL + # column name used unquoted in arrange() below; avoids an R CMD check note + Status <- NULL if (is.null(currency)) { currency <- if (is.null(attr(x, "currency"))) "$" else attr(x, "currency") } ref_str <- check_ref_str(ref_str, x$Strategy) check_wtp_nhb(wtp, nhb = FALSE) - if (ncol(x) > 7) { - # reformat icers class object if uncertainty bounds are present - x <- x %>% - select(Strategy, Cost, Effect, - Inc_Cost, Inc_Effect, - ICER, Status) - } + # keep only the columns the plot uses, as a plain data frame, so the plot data are the same + # whether or not x has uncertainty bounds, reference columns, or stored attributes + v_plot_cols <- c("Strategy", "Cost", "Effect", "Inc_Cost", "Inc_Effect", "ICER", "Status") + x <- data.frame(unclass(x)[v_plot_cols], check.names = FALSE, stringsAsFactors = FALSE) # type checking label <- match.arg(label) diff --git a/tests/testthat/test_currency.R b/tests/testthat/test_currency.R index 65cf20f..fbc3e12 100644 --- a/tests/testthat/test_currency.R +++ b/tests/testthat/test_currency.R @@ -1,4 +1,4 @@ -context("the currency of a psa object carries through to results, plots, and tables (#203)") +# the currency of a psa object carries through to results, plots, and tables (#203) cancer_psa_data <- dampack::cancer_psa_data psa_eur <- make_psa_obj(cancer_psa_data$cost, cancer_psa_data$effectiveness, diff --git a/tests/testthat/test_icers_reference.R b/tests/testthat/test_icers_reference.R index e534651..89f9c4b 100644 --- a/tests/testthat/test_icers_reference.R +++ b/tests/testthat/test_icers_reference.R @@ -1,4 +1,4 @@ -context("calculate_icers() against a reference strategy (#209) and net benefit (#200)") +# calculate_icers() against a reference strategy (#209) and net benefit (#200) # Toy example with one strategy in each position relative to the reference "Ref": # strategy cost effect vs Ref: inc cost inc effect status diff --git a/tests/testthat/test_psa_reference.R b/tests/testthat/test_psa_reference.R index 596fbc3..047a580 100644 --- a/tests/testthat/test_psa_reference.R +++ b/tests/testthat/test_psa_reference.R @@ -1,4 +1,4 @@ -context("summary.psa() and calculate_icers_psa() against a reference strategy (#209, #202)") +# summary.psa() and calculate_icers_psa() against a reference strategy (#209, #202) # Four PSA samples; the difference "New" - "Ref" falls in a different quadrant in each: # sample inc effect inc cost quadrant diff --git a/tests/testthat/test_reference_plots.R b/tests/testthat/test_reference_plots.R index cd7ca2a..f252a6e 100644 --- a/tests/testthat/test_reference_plots.R +++ b/tests/testthat/test_reference_plots.R @@ -1,4 +1,4 @@ -context("reference strategy and WTP lines in plot.icers() and plot.psa() (#209, #202)") +# reference strategy and WTP lines in plot.icers() and plot.psa() (#209, #202) df_toy <- data.frame(strategy = c("Standard of care", "New drug (A)", "Cheaper", "Worse"), cost = c(100, 200, 50, 300), From 64c6584328c38e3b95f63f4bec653075c897a593 Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Fri, 13 Nov 2026 17:11:39 -0800 Subject: [PATCH 07/10] plot.psa(): xtrans/ytrans, with ellipses computed on the transformed scale (#201) The ellipses were computed on the data scale, so on log axes (added with scale_*_log10()) they lost their shape and any part below zero became NaN. plot.psa() now takes xtrans and ytrans, passes them to its own scales, and computes each ellipse from the transformed samples before mapping it back. Values a transformation cannot show (zero or negative on a log scale, common on the incremental plane) give an informative error. With the default identity transformations the plots are unchanged. The duplicated ellipse code of the two planes is now one helper, psa_ellipses(). --- NEWS.md | 1 + R/psa.R | 82 +++++++++++++++++++++++++++++-------- man/check_axis_transform.Rd | 26 ++++++++++++ man/plot.psa.Rd | 8 ++++ man/psa_ellipses.Rd | 28 +++++++++++++ tests/testthat/test_psa.R | 41 +++++++++++++++++++ 6 files changed, 168 insertions(+), 18 deletions(-) create mode 100644 man/check_axis_transform.Rd create mode 100644 man/psa_ellipses.Rd diff --git a/NEWS.md b/NEWS.md index 626c49a..5d3ad80 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,7 @@ ## New features +- `plot.psa()` gains `xtrans` and `ytrans` to put the effectiveness and cost axes on, for example, a log scale. The ellipses are computed on the transformed scale, so they keep their shape instead of breaking where they cross zero; values a log axis cannot show give an informative error (#201). - The currency of a `psa` object now carries through to its analyses: `ceac()`, `calc_exp_loss()`, `calc_evpi()`, `calc_evppi()`, `calc_evsi()`, and `calculate_icers_psa()` keep it, and their `plot()` and `print()` methods use it unless `currency` is given. `plot.ceac()` gains `effect_units` (#203). - `summary.psa()` gains `ref_str` and `wtp`. With a reference strategy it adds the mean incremental cost and effect and the proportion of PSA samples in each quadrant of the incremental cost-effectiveness plane (`propNE`, `propSE`, `propSW`, `propNW`); with `wtp` it adds the mean NMB and, with a reference, `meanIncNMB` and the proportion of samples that are cost-effective compared with the reference (`propCostEffective`) (#209, #202). - `calculate_icers_psa()` gains `ref_str`, `wtp`, and `nhb`. With `uncertainty = TRUE` and a reference strategy, it adds 95% intervals for the differences from the reference, computed sample by sample (#209). diff --git a/R/psa.R b/R/psa.R index 8f98e8e..4bfc556 100644 --- a/R/psa.R +++ b/R/psa.R @@ -188,6 +188,11 @@ summary.psa <- function(object, calc_sds = FALSE, ref_str = NULL, wtp = NULL, .. #' cost-effectiveness plane. Without \code{ref_str}, the line goes through the mean cost and effect #' of the least costly strategy, as in \code{\link{plot.icers}}. Samples below the line are #' cost-effective compared with that strategy at this threshold. +#' @param xtrans,ytrans transformation of the effectiveness (x) and cost (y) axes, such as +#' \code{"log10"}, passed to \code{\link[ggplot2]{scale_continuous}}. Defaults to +#' \code{"identity"}. The ellipses are computed on the transformed scale, so they keep their +#' shape on a log axis; the center points stay at the arithmetic means. A log axis needs every +#' value on it to be positive, which on the incremental plane (\code{ref_str}) is rarely the case. #' @inheritParams add_common_aes #' #' @importFrom ellipse ellipse @@ -211,6 +216,8 @@ plot.psa <- function(x, ref_axis = TRUE, ref_caption = TRUE, wtp = NULL, + xtrans = "identity", + ytrans = "identity", ...) { Effectiveness <- Cost <- Strategy <- Eff.mean <- Cost.mean <- y <- group <- NULL @@ -243,6 +250,7 @@ plot.psa <- function(x, # make strategies in psa object into ordered factors df_ce$Strategy <- factor(df_ce$Strategy, levels = v_strategies, ordered = TRUE) + check_axis_transform(df_ce, xtrans, ytrans) psa_plot <- ggplot(df_ce, aes(x = Effectiveness, y = Cost, color = Strategy)) + geom_point(size = 0.7, alpha = alpha, shape = 21) + ylab(paste("Cost (", currency, ")", sep = "")) @@ -263,15 +271,7 @@ plot.psa <- function(x, if (ellipse) { # make points for ellipse plotting - l_ell <- lapply(v_strategies, function(s) { - df_strat_specific <- df_ce[df_ce$Strategy == s, ] - els <- with(df_strat_specific, - ellipse(cor(Effectiveness, Cost), - scale = c(sd(Effectiveness), sd(Cost)), - centre = c(mean(Effectiveness), mean(Cost)))) - data.frame(els, group = s, stringsAsFactors = FALSE) - }) - df_ell <- bind_rows(l_ell) + df_ell <- psa_ellipses(df_ce, v_strategies, xtrans, ytrans) # draw ellipse lines psa_plot <- psa_plot + geom_path(data = df_ell, aes(x = x, y = y, colour = group), @@ -299,6 +299,7 @@ plot.psa <- function(x, n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks, xbreaks = xbreaks, ybreaks = ybreaks, xlim = xlim, ylim = ylim, + xtrans = xtrans, ytrans = ytrans, v_str = v_strategies) } else { @@ -333,6 +334,7 @@ plot.psa <- function(x, df_ice$Strategy <- factor(df_ice$Strategy, levels = v_comp_strategies, ordered = TRUE) + check_axis_transform(df_ice, xtrans, ytrans, incremental = TRUE) psa_plot <- ggplot(df_ice, aes(x = Effectiveness, y = Cost, color = Strategy)) + geom_point(size = 0.7, alpha = alpha, shape = 21) + ylab(paste("Incremental Cost (", currency, ")", sep = "")) + @@ -372,15 +374,7 @@ plot.psa <- function(x, if (ellipse) { # make points for ellipse plotting - l_ell <- lapply(v_comp_strategies, function(s) { - df_strat_specific <- df_ice[df_ice$Strategy == s, ] - els <- with(df_strat_specific, - ellipse(cor(Effectiveness, Cost), - scale = c(sd(Effectiveness), sd(Cost)), - centre = c(mean(Effectiveness), mean(Cost)))) - data.frame(els, group = s, stringsAsFactors = FALSE) - }) - df_ell <- bind_rows(l_ell) + df_ell <- psa_ellipses(df_ice, v_comp_strategies, xtrans, ytrans) # draw ellipse lines psa_plot <- psa_plot + geom_path(data = df_ell, aes(x = x, y = y, colour = group), @@ -396,7 +390,59 @@ plot.psa <- function(x, n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks, xbreaks = xbreaks, ybreaks = ybreaks, xlim = xlim, ylim = ylim, + xtrans = xtrans, ytrans = ytrans, v_str = v_strategies) } } + +#' Ellipses around each strategy's PSA samples +#' +#' Each ellipse is computed from the mean, standard deviation and correlation of the samples on +#' the transformed scale of the axes and mapped back, so that it keeps its shape when the axes +#' are, for example, on a log scale. With identity transformations this is the usual ellipse. +#' +#' @param df_samples data frame with columns \code{Strategy}, \code{Effectiveness} and \code{Cost}. +#' @param v_str strategies to draw an ellipse for. +#' @inheritParams plot.psa +#' @return a data frame with columns \code{x}, \code{y} and \code{group}. +#' @keywords internal +psa_ellipses <- function(df_samples, v_str, xtrans, ytrans) { + tr_x <- scales::as.transform(xtrans) + tr_y <- scales::as.transform(ytrans) + l_ell <- lapply(v_str, function(s) { + v_sel <- df_samples$Strategy == s + # samples on the scale of the axes + v_x <- tr_x$transform(df_samples$Effectiveness[v_sel]) + v_y <- tr_y$transform(df_samples$Cost[v_sel]) + m_ell <- ellipse(cor(v_x, v_y), scale = c(sd(v_x), sd(v_y)), centre = c(mean(v_x), mean(v_y))) + # back to the data scale, where ggplot2 applies the axis transformation again + data.frame(x = tr_x$inverse(m_ell[, 1]), y = tr_y$inverse(m_ell[, 2]), + group = s, stringsAsFactors = FALSE) + }) + bind_rows(l_ell) +} + +#' Check that the PSA samples can be shown on transformed axes +#' +#' @param df_samples data frame with columns \code{Effectiveness} and \code{Cost}. +#' @param incremental whether the samples are differences from a reference strategy. +#' @inheritParams plot.psa +#' @return \code{NULL}, invisibly; called for the error. +#' @keywords internal +check_axis_transform <- function(df_samples, xtrans, ytrans, incremental = FALSE) { + l_axes <- list(list(xtrans, df_samples$Effectiveness, "xtrans", "effectiveness"), + list(ytrans, df_samples$Cost, "ytrans", "cost")) + for (axis in l_axes) { + tr <- scales::as.transform(axis[[1]]) + if (!all(is.finite(suppressWarnings(tr$transform(axis[[2]]))))) { + tr_name <- if (is.character(axis[[1]])) axis[[1]] else tr$name + stop("`", axis[[3]], " = \"", tr_name, "\"` cannot show every ", + if (incremental) "incremental ", axis[[4]], " value: some are outside its domain ", + "(zero or negative, for a log scale)", + if (incremental) ". Differences from the reference strategy are often negative", + ".", call. = FALSE) + } + } + invisible(NULL) +} diff --git a/man/check_axis_transform.Rd b/man/check_axis_transform.Rd new file mode 100644 index 0000000..f6065f1 --- /dev/null +++ b/man/check_axis_transform.Rd @@ -0,0 +1,26 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/psa.R +\name{check_axis_transform} +\alias{check_axis_transform} +\title{Check that the PSA samples can be shown on transformed axes} +\usage{ +check_axis_transform(df_samples, xtrans, ytrans, incremental = FALSE) +} +\arguments{ +\item{df_samples}{data frame with columns \code{Effectiveness} and \code{Cost}.} + +\item{xtrans, ytrans}{transformation of the effectiveness (x) and cost (y) axes, such as +\code{"log10"}, passed to \code{\link[ggplot2]{scale_continuous}}. Defaults to +\code{"identity"}. The ellipses are computed on the transformed scale, so they keep their +shape on a log axis; the center points stay at the arithmetic means. A log axis needs every +value on it to be positive, which on the incremental plane (\code{ref_str}) is rarely the case.} + +\item{incremental}{whether the samples are differences from a reference strategy.} +} +\value{ +\code{NULL}, invisibly; called for the error. +} +\description{ +Check that the PSA samples can be shown on transformed axes +} +\keyword{internal} diff --git a/man/plot.psa.Rd b/man/plot.psa.Rd index ac144a5..67391ea 100644 --- a/man/plot.psa.Rd +++ b/man/plot.psa.Rd @@ -21,6 +21,8 @@ ref_axis = TRUE, ref_caption = TRUE, wtp = NULL, + xtrans = "identity", + ytrans = "identity", ... ) } @@ -66,6 +68,12 @@ cost-effectiveness plane. Without \code{ref_str}, the line goes through the mean of the least costly strategy, as in \code{\link{plot.icers}}. Samples below the line are cost-effective compared with that strategy at this threshold.} +\item{xtrans, ytrans}{transformation of the effectiveness (x) and cost (y) axes, such as +\code{"log10"}, passed to \code{\link[ggplot2]{scale_continuous}}. Defaults to +\code{"identity"}. The ellipses are computed on the transformed scale, so they keep their +shape on a log axis; the center points stay at the arithmetic means. A log axis needs every +value on it to be positive, which on the incremental plane (\code{ref_str}) is rarely the case.} + \item{...}{further arguments to plot. This is not used by \code{dampack} but required for generic consistency.} } diff --git a/man/psa_ellipses.Rd b/man/psa_ellipses.Rd new file mode 100644 index 0000000..0bd5f29 --- /dev/null +++ b/man/psa_ellipses.Rd @@ -0,0 +1,28 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/psa.R +\name{psa_ellipses} +\alias{psa_ellipses} +\title{Ellipses around each strategy's PSA samples} +\usage{ +psa_ellipses(df_samples, v_str, xtrans, ytrans) +} +\arguments{ +\item{df_samples}{data frame with columns \code{Strategy}, \code{Effectiveness} and \code{Cost}.} + +\item{v_str}{strategies to draw an ellipse for.} + +\item{xtrans, ytrans}{transformation of the effectiveness (x) and cost (y) axes, such as +\code{"log10"}, passed to \code{\link[ggplot2]{scale_continuous}}. Defaults to +\code{"identity"}. The ellipses are computed on the transformed scale, so they keep their +shape on a log axis; the center points stay at the arithmetic means. A log axis needs every +value on it to be positive, which on the incremental plane (\code{ref_str}) is rarely the case.} +} +\value{ +a data frame with columns \code{x}, \code{y} and \code{group}. +} +\description{ +Each ellipse is computed from the mean, standard deviation and correlation of the samples on +the transformed scale of the axes and mapped back, so that it keeps its shape when the axes +are, for example, on a log scale. With identity transformations this is the usual ellipse. +} +\keyword{internal} diff --git a/tests/testthat/test_psa.R b/tests/testthat/test_psa.R index f627bbe..8ec331e 100644 --- a/tests/testthat/test_psa.R +++ b/tests/testthat/test_psa.R @@ -108,3 +108,44 @@ test_that("make_psa_obj() names other_outcome columns after the strategies", { p <- make_psa_obj(df_cost, df_cost, strategies = c("A", "B", "C"), other_outcome = df_other) expect_identical(names(p$other_outcome), c("A", "B", "C")) }) + +# log axes (#201): the ellipse is computed on the scale of the axes +test_that("plot.psa(xtrans, ytrans) draws the ellipses on log axes", { + p <- plot(psa_big, xtrans = "log10", ytrans = "log10") + expect_no_warning(b <- ggplot2::ggplot_build(p)) + expect_equal(b$layout$panel_scales_x[[1]]$trans$name, "log-10") + expect_equal(b$layout$panel_scales_y[[1]]$trans$name, "log-10") + i_path <- which(vapply(p$layers, function(l) inherits(l$geom, "GeomPath"), logical(1))) + df_ell <- ggplot2::layer_data(p, i_path) + # layer data are on the axis scale (log10) and finite: no part of an ellipse falls below 0 + expect_true(all(is.finite(df_ell$x) & is.finite(df_ell$y))) + # each ellipse is the usual ellipse of the log10 samples + v_lcost <- log10(psa_big$cost[["Chemo"]]) + v_leff <- log10(psa_big$effectiveness[["Chemo"]]) + m_ell <- ellipse::ellipse(cor(v_leff, v_lcost), scale = c(sd(v_leff), sd(v_lcost)), + centre = c(mean(v_leff), mean(v_lcost))) + df_chemo <- df_ell[df_ell$group == which(psa_big$strategies == "Chemo"), ] + expect_equal(unname(as.matrix(df_chemo[, c("x", "y")])), unname(m_ell)) +}) + +test_that("plot.psa() with the default identity axes keeps the usual ellipse", { + p <- plot(psa_big) + i_path <- which(vapply(p$layers, function(l) inherits(l$geom, "GeomPath"), logical(1))) + df_ell <- p$layers[[i_path]]$data + v_cost <- psa_big$cost[["Chemo"]] + v_eff <- psa_big$effectiveness[["Chemo"]] + m_ell <- ellipse::ellipse(cor(v_eff, v_cost), scale = c(sd(v_eff), sd(v_cost)), + centre = c(mean(v_eff), mean(v_cost))) + expect_equal(unname(as.matrix(df_ell[df_ell$group == "Chemo", c("x", "y")])), unname(m_ell)) +}) + +test_that("plot.psa() explains when values cannot be shown on a log axis", { + expect_error(plot(psa_big, ref_str = "Chemo", ytrans = "log10"), + "`ytrans = \"log10\"` cannot show every incremental cost value") + df_cost_zero <- psa_big$cost + df_cost_zero[1, 1] <- 0 + psa_zero <- make_psa_obj(df_cost_zero, psa_big$effectiveness, psa_big$parameters, + psa_big$strategies) + expect_error(plot(psa_zero, ytrans = "log10"), "cannot show every cost value") + expect_s3_class(plot(psa_zero, xtrans = "log10"), "ggplot") +}) From 95dcc22d691598095c6b54b79141e9d134c2618c Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Fri, 13 Nov 2026 17:26:00 -0800 Subject: [PATCH 08/10] Harmonize the API with soft deprecation (#214): ceac(psa, wtp), linewidth, axis limits, effect_units - ceac() takes the psa object first, like calc_exp_loss() and calc_evpi(). The old positional ceac(wtp, psa) still works with lifecycle::deprecate_soft(); named calls work in any order. - plot.owsa() and plot.exp_loss() take linewidth; size and lsize still work, deprecated. - plot.owsa() and plot.twsa() gain xlim/ylim, owsa_opt_strat() gains xlim. - effect_units defaults to "QALYs" in every plot; per_unit() gives the singular for willingness-to-pay labels, so default labels are unchanged ("$/QALY"). - lifecycle (>= 1.0.0) added to Imports. - API style decision record in .github/CONTRIBUTING.md, including the open 2.0 questions. --- .github/CONTRIBUTING.md | 27 +++++++++++ DESCRIPTION | 1 + NAMESPACE | 3 ++ NEWS.md | 3 ++ R/add_common_aes.R | 12 +++++ R/ceac.R | 27 ++++++++--- R/evpi.R | 8 ++-- R/evppi.R | 8 ++-- R/evsi.R | 8 ++-- R/exp_loss.R | 22 ++++++--- R/icers.R | 2 +- R/owsa.R | 24 +++++++--- R/twsa.R | 3 ++ man/ceac.Rd | 12 +++-- man/owsa_opt_strat.Rd | 5 +- man/per_unit.Rd | 19 ++++++++ man/plot.ceac.Rd | 6 ++- man/plot.evpi.Rd | 6 ++- man/plot.evppi.Rd | 6 ++- man/plot.evsi.Rd | 6 ++- man/plot.exp_loss.Rd | 13 ++++-- man/plot.owsa.Rd | 12 ++++- man/plot.twsa.Rd | 6 +++ tests/testthat/test_api_harmonize.R | 68 ++++++++++++++++++++++++++++ tests/testthat/test_ceac.R | 14 +++--- tests/testthat/test_currency.R | 8 ++-- tests/testthat/test_elc.R | 4 +- tests/testthat/test_plot_options.R | 2 +- tests/testthat/test_strategy_names.R | 4 +- 29 files changed, 275 insertions(+), 64 deletions(-) create mode 100644 man/per_unit.Rd create mode 100644 tests/testthat/test_api_harmonize.R diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index b4204be..8c6e40d 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -79,6 +79,33 @@ Exported function and argument names are part of the public API that users' scri New exported functions start with a verb (`calculate_`, `make_`, `plot_`, ...), and new arguments follow the names already used elsewhere in the package (`psa`, `wtp`, `currency`, `effect_units`, `txtsize`, `col`). +### API style (decision record, #214) + +Adopted for dampack 1.1.0 (November 2026). It records the names the package uses now, so new code follows them, and the targets for 2.0 that the group still has to agree on. Nothing below renames an existing function or argument in 1.x except through soft deprecation. + +**Argument order.** The data object comes first, then the threshold: `calc_exp_loss(psa, wtp)`, `calc_evpi(psa, wtp)`, `calc_evppi(psa, wtp, ...)`, `calc_evsi(psa, wtp, ...)`, `owsa(sa_obj, ...)`, `twsa(sa_obj, ...)`. Since 1.1.0 `ceac(psa, wtp)` does too; the old positional `ceac(wtp, psa)` still works with a soft deprecation warning. + +**Plot arguments.** A plot method uses these names whenever it has the option, with these meanings: + +| Argument | Meaning | +|---|---| +| `txtsize` | base text size | +| `col` | `c("access", "full", "bw")`: accessible (viridis), full color, or black and white. Only where strategies or groups are told apart by color; `plot.icers()` (shape and line type), `plot.evpi()` and `plot.evppi()` (one line) have none | +| `currency` | `NULL` uses the currency stored in the object (from `make_psa_obj()` or `calculate_icers()`), otherwise `"$"` | +| `effect_units` | units of effectiveness in the plural, default `"QALYs"`; labels that mean "per unit" use the singular (`"$/QALY"`) | +| `n_x_ticks`, `n_y_ticks`, `xbreaks`, `ybreaks` | approximate number of ticks, or exact breaks | +| `xlim`, `ylim` | limits of each continuous axis (`NULL` sets them automatically) | +| `xtrans`, `ytrans` | axis transformations such as `"log10"` (`plot.psa()`) | +| `linewidth` | line width, as in ggplot2. `plot.owsa(size)` and `plot.exp_loss(lsize)` are deprecated in its favor | + +**Open questions for 2.0** (meeting decision 3; no aliases are added in 1.1.0): + +- Verb prefixes: the package has both `calc_` (`calc_evpi()`, `calc_exp_loss()`) and `calculate_` (`calculate_icers()`, `calculate_icers_psa()`). +- `effect` (`calculate_icers()`) versus `effectiveness` (`make_psa_obj()` and the `psa` object). +- Column case: most result tables use capitalized columns (`Strategy`, `Cost`, `WTP`, `Proportion`), while `owsa` and `twsa` objects use lower case (`strategy`, `parameter`, `outcome_val`). Until this is decided, new columns follow the existing style of their object. + +**Accepted minor break in 1.1.0.** `summary.ceac()` renames its third column from `cost_eff_strat` to `optimal_strategy` (#173), as recorded in NEWS.md. + ### Files and tests - Source files live in `R/`, one family of functions per file. diff --git a/DESCRIPTION b/DESCRIPTION index bd0dad3..fbd1e15 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -59,6 +59,7 @@ Imports: triangle, ggrepel, tidyr, + lifecycle (>= 1.0.0), rlang, viridis, RColorBrewer diff --git a/NAMESPACE b/NAMESPACE index 7958a75..4fb5b30 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -46,6 +46,9 @@ importFrom(dplyr,bind_cols) importFrom(ellipse,ellipse) importFrom(ggrepel,geom_label_repel) importFrom(grDevices,grey.colors) +importFrom(lifecycle,deprecate_soft) +importFrom(lifecycle,deprecated) +importFrom(lifecycle,is_present) importFrom(mgcv,Predict.matrix) importFrom(mgcv,PredictMat) importFrom(mgcv,gam) diff --git a/NEWS.md b/NEWS.md index 626c49a..abb27b2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,7 @@ ## New features +- Plot arguments are more consistent across methods (#214): `plot.owsa()` and `plot.exp_loss()` take `linewidth` (as in ggplot2); `plot.owsa()` and `plot.twsa()` gain `xlim` and `ylim`, and `owsa_opt_strat()` gains `xlim`; `effect_units` defaults to `"QALYs"` in every plot, and willingness-to-pay labels use its singular ("$/QALY"). The naming rules are recorded in an API style section of CONTRIBUTING.md. - The currency of a `psa` object now carries through to its analyses: `ceac()`, `calc_exp_loss()`, `calc_evpi()`, `calc_evppi()`, `calc_evsi()`, and `calculate_icers_psa()` keep it, and their `plot()` and `print()` methods use it unless `currency` is given. `plot.ceac()` gains `effect_units` (#203). - `summary.psa()` gains `ref_str` and `wtp`. With a reference strategy it adds the mean incremental cost and effect and the proportion of PSA samples in each quadrant of the incremental cost-effectiveness plane (`propNE`, `propSE`, `propSW`, `propNW`); with `wtp` it adds the mean NMB and, with a reference, `meanIncNMB` and the proportion of samples that are cost-effective compared with the reference (`propCostEffective`) (#209, #202). - `calculate_icers_psa()` gains `ref_str`, `wtp`, and `nhb`. With `uncertainty = TRUE` and a reference strategy, it adds 95% intervals for the differences from the reference, computed sample by sample (#209). @@ -18,6 +19,8 @@ ## Superseded +- `ceac()` now takes the `psa` object first, like `calc_exp_loss()` and `calc_evpi()`: `ceac(psa, wtp)`. The old positional order `ceac(wtp, psa)` still works but gives a soft deprecation warning; named arguments work in either order (#214). +- `plot.owsa(size = )` and `plot.exp_loss(lsize = )` are deprecated in favor of `linewidth`; the old arguments still work, with a soft deprecation warning (#214). - `example_psa` and `example_psa_obj` are superseded by `cancer_psa_data`, which contains the same PSA samples. Both remain available for backward compatibility and will be removed in dampack 2.0. They are now rebuilt from `cancer_psa_data` when the package is installed, so the samples are stored only once. ## Breaking changes diff --git a/R/add_common_aes.R b/R/add_common_aes.R index 5e8bd5a..c26b626 100644 --- a/R/add_common_aes.R +++ b/R/add_common_aes.R @@ -279,3 +279,15 @@ resolve_currency <- function(currency, x) { voi_units <- function(x, currency, effect_units) { if (identical(attr(x, "outcome"), "nhb")) effect_units else currency } + +#' Singular form of the effect units, for "per unit" labels +#' +#' Drops a final "s", so \code{"QALYs"} becomes \code{"QALY"} in labels such as "$/QALY". A unit +#' already in the singular is returned unchanged. +#' +#' @param effect_units units of effectiveness, such as \code{"QALYs"}. +#' @return a string. +#' @keywords internal +per_unit <- function(effect_units) { + sub("s$", "", effect_units) +} diff --git a/R/ceac.R b/R/ceac.R index 2817f0d..62d2549 100644 --- a/R/ceac.R +++ b/R/ceac.R @@ -5,10 +5,14 @@ #' \code{ceac} is used to compute and plot the cost-effectiveness acceptability #' curves (CEAC) from a probabilistic sensitivity analysis (PSA) dataset. #' -#' @param wtp numeric vector with willingness-to-pay (WTP) thresholds #' @param psa psa object from \code{\link{make_psa_obj}} +#' @param wtp numeric vector with willingness-to-pay (WTP) thresholds #' @keywords cost-effectiveness acceptability curves #' @details +#' Like \code{\link{calc_exp_loss}} and \code{\link{calc_evpi}}, \code{ceac} takes the +#' \code{psa} object first. The order used before dampack 1.1.0, \code{ceac(wtp, psa)}, still +#' works but is deprecated; named arguments work in any order. +#' #' \code{ceac} computes the probability of each of the strategies being #' cost-effective at each \code{wtp} threshold. The returned object has classes #' \code{ceac} and \code{data.frame}, and has its own plot method (\code{\link{plot.ceac}}). @@ -28,7 +32,7 @@ #' #' # define wtp threshold vector (can also use a single wtp) #' wtp <- seq(1e4, 1e5, by = 1e4) -#' ceac_obj <- ceac(wtp, psa_cancer) +#' ceac_obj <- ceac(psa_cancer, wtp) #' plot(ceac_obj) # see ?plot.ceac for options #' #' # this is most useful when there are many strategies @@ -54,8 +58,17 @@ #' #' #' @importFrom tidyr pivot_longer +#' @importFrom lifecycle deprecate_soft deprecated is_present #' @export -ceac <- function(wtp, psa) { +ceac <- function(psa, wtp) { + # the order before 1.1.0 was ceac(wtp, psa): accept it, with a soft deprecation warning + if (inherits(wtp, "psa") && !inherits(psa, "psa")) { + deprecate_soft("1.1.0", "ceac(wtp = 'must come after `psa`')", + details = "Use `ceac(psa, wtp)`, the order of `calc_exp_loss()` and `calc_evpi()`.") + tmp <- psa + psa <- wtp + wtp <- tmp + } # check that psa has class 'psa' check_psa_object(psa) @@ -139,7 +152,9 @@ ceac <- function(wtp, psa) { #' @param currency string with currency used in the cost-effectiveness analysis (CEA). #' Defaults to the currency of the PSA the CEAC was computed from (or \code{$}), but can be any #' currency symbol or word (e.g., £, €, peso). -#' @param effect_units units of effectiveness, used in the x-axis label. Default: QALY +#' @param effect_units units of effectiveness, in the plural (for example \code{"QALYs"} or +#' \code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +#' ("$/QALY"), and a value already in the singular is used as given. #' @param min_prob minimum probability to show strategy in plot. #' For example, if the min_prob is 0.05, only strategies that ever #' exceed Pr(Cost Effective) = 0.05 will be plotted. Most useful in situations @@ -172,7 +187,7 @@ plot.ceac <- function(x, ylim = NULL, xlim = c(0, NA), col = c("access", "full", "bw"), - effect_units = "QALY", + effect_units = "QALYs", ...) { currency <- resolve_currency(currency, x) wtp_name <- "WTP" @@ -224,7 +239,7 @@ plot.ceac <- function(x, y = !!sym(prop_name), color = !!sym(strat_name))) + geom_line() + - xlab(paste("Willingness to Pay (Thousand ", currency, " / ", effect_units, ")", sep = "")) + + xlab(paste("Willingness to Pay (Thousand ", currency, " / ", per_unit(effect_units), ")", sep = "")) + ylab("Pr Most Cost-Effective") if (points) { diff --git a/R/evpi.R b/R/evpi.R index 237e3bb..d4be944 100644 --- a/R/evpi.R +++ b/R/evpi.R @@ -69,7 +69,9 @@ calc_evpi <- function(psa, wtp, pop = 1) { #' @param currency string with currency used in the cost-effectiveness analysis (CEA). #' Default: the currency of the PSA the results were computed from (or $), but it could be any #' currency symbol or word (e.g., £, €, peso) -#' @param effect_units units of effectiveness. Default: QALY +#' @param effect_units units of effectiveness, in the plural (for example \code{"QALYs"} or +#' \code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +#' ("$/QALY"), and a value already in the singular is used as given. #' @inheritParams add_common_aes #' @keywords expected value of perfect information #' @return A \code{ggplot2} plot with the EVPI @@ -80,7 +82,7 @@ calc_evpi <- function(psa, wtp, pop = 1) { plot.evpi <- function(x, txtsize = 12, currency = NULL, - effect_units = "QALY", + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -94,7 +96,7 @@ plot.evpi <- function(x, g <- ggplot(data = x, aes(x = WTP_thou, y = EVPI)) + geom_line() + - xlab(paste("Willingness to Pay (Thousand ", currency, "/", effect_units, ")", sep = "")) + + xlab(paste("Willingness to Pay (Thousand ", currency, "/", per_unit(effect_units), ")", sep = "")) + ylab(paste("EVPI (", currency, ")", sep = "")) add_common_aes(g, txtsize, continuous = c("x", "y"), n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks, diff --git a/R/evppi.R b/R/evppi.R index 483b7ff..2719cb7 100644 --- a/R/evppi.R +++ b/R/evppi.R @@ -143,7 +143,9 @@ calc_evppi <- function(psa, #' @param currency string with currency used in the cost-effectiveness analysis (CEA). #' Default: the currency of the PSA the results were computed from (or $), but it could be any #' currency symbol or word (e.g., £, €, peso) -#' @param effect_units units of effectiveness. Default: QALY +#' @param effect_units units of effectiveness, in the plural (for example \code{"QALYs"} or +#' \code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +#' ("$/QALY"), and a value already in the singular is used as given. #' @inheritParams add_common_aes #' @keywords expected value of perfect information #' @return A \code{ggplot2} plot with the EVPPI @@ -154,7 +156,7 @@ calc_evppi <- function(psa, plot.evppi <- function(x, txtsize = 12, currency = NULL, - effect_units = "QALY", + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -170,7 +172,7 @@ plot.evppi <- function(x, g <- ggplot(data = x, aes(x = WTP_thou, y = EVPPI)) + geom_line() + - xlab(paste("Willingness to Pay (Thousand ", currency, "/", effect_units, ")", sep = "")) + + xlab(paste("Willingness to Pay (Thousand ", currency, "/", per_unit(effect_units), ")", sep = "")) + ylab(paste("EVPPI (", v_units, ")", sep = "")) add_common_aes(g, txtsize, continuous = c("x", "y"), n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks, diff --git a/R/evsi.R b/R/evsi.R index 5a5f42d..4968bae 100644 --- a/R/evsi.R +++ b/R/evsi.R @@ -287,7 +287,9 @@ predict_matrix_tensor_smooth_ga <- function(object, #' @param currency string with currency used in the cost-effectiveness analysis (CEA). #' Default: the currency of the PSA the results were computed from (or $), but it could be any #' currency symbol or word (e.g., £, €, peso) -#' @param effect_units units of effectiveness. Default: QALY +#' @param effect_units units of effectiveness, in the plural (for example \code{"QALYs"} or +#' \code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +#' ("$/QALY"), and a value already in the singular is used as given. #' @inheritParams add_common_aes #' @keywords expected value of sample information #' @return A \code{ggplot2} plot with the EVSI @@ -298,7 +300,7 @@ predict_matrix_tensor_smooth_ga <- function(object, plot.evsi <- function(x, txtsize = 12, currency = NULL, - effect_units = "QALY", + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -317,7 +319,7 @@ plot.evsi <- function(x, if (length(unique(x$WTP)) == 1) { col <- "bw" } - scale_text <- paste("Willingness to Pay\n(Thousand ", currency, "/", effect_units, ")", sep = "") + scale_text <- paste("Willingness to Pay\n(Thousand ", currency, "/", per_unit(effect_units), ")", sep = "") if (length(unique(x$WTP)) == 1 && "n" %in% names(x)) { g <- ggplot(data = x, diff --git a/R/exp_loss.R b/R/exp_loss.R index 368b5e5..05a9a3d 100644 --- a/R/exp_loss.R +++ b/R/exp_loss.R @@ -100,12 +100,15 @@ calc_exp_loss <- function(psa, wtp) { #' @param currency string with currency used in the cost-effectiveness analysis (CEA). #' Default: the currency of the PSA the results were computed from (or $), but it could be any #' currency symbol or word (e.g., £, €, peso) -#' @param effect_units units of effectiveness. Default: QALY +#' @param effect_units units of effectiveness, in the plural (for example \code{"QALYs"} or +#' \code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +#' ("$/QALY"), and a value already in the singular is used as given. #' @param log_y take the base 10 log of the y axis #' @param frontier indicate the frontier (also the expected value of perfect information). #' To only plot the EVPI see \code{\link{calc_evpi}}. #' @param points whether to plot points on the curve (TRUE) or not (FALSE) -#' @param lsize line size. defaults to 1. +#' @param linewidth width of the lines. Defaults to 1. +#' @param lsize deprecated; use \code{linewidth} instead. #' @inheritParams add_common_aes #' #' @return A \code{ggplot2} object with the expected loss @@ -118,10 +121,10 @@ plot.exp_loss <- function(x, log_y = TRUE, frontier = TRUE, points = TRUE, - lsize = 1, + linewidth = 1, txtsize = 12, currency = NULL, - effect_units = "QALY", + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -129,7 +132,12 @@ plot.exp_loss <- function(x, xlim = c(0, NA), ylim = NULL, col = c("access", "full", "bw"), + lsize = deprecated(), ...) { + if (is_present(lsize)) { + deprecate_soft("1.1.0", "plot.exp_loss(lsize)", "plot.exp_loss(linewidth)") + linewidth <- lsize + } On_Frontier <- NULL currency <- resolve_currency(currency, x) wtp_name <- "WTP_thou" @@ -154,7 +162,7 @@ plot.exp_loss <- function(x, p <- ggplot(data = df_nofront, aes(x = !!sym(wtp_name), y = !!sym(loss_name))) + - xlab(paste0("Willingness to Pay (Thousand ", currency, "/", effect_units, ")")) + + xlab(paste0("Willingness to Pay (Thousand ", currency, "/", per_unit(effect_units), ")")) + ylab(paste0("Expected Loss (", currency, ")")) # color @@ -165,7 +173,7 @@ plot.exp_loss <- function(x, p <- p + geom_point(aes(color = !!sym(strat_name))) } p <- p + - geom_line(linewidth = lsize, aes(color = !!sym(strat_name))) + geom_line(linewidth = linewidth, aes(color = !!sym(strat_name))) } if (col == "bw") { @@ -173,7 +181,7 @@ plot.exp_loss <- function(x, p <- p + geom_point() } p <- p + - geom_line(linewidth = lsize, aes(linetype = !!sym(strat_name))) + geom_line(linewidth = linewidth, aes(linetype = !!sym(strat_name))) } # in black and white, strategies are told apart by line type, so no color scale is added diff --git a/R/icers.R b/R/icers.R index 3bb7a2f..449bbe5 100644 --- a/R/icers.R +++ b/R/icers.R @@ -222,7 +222,7 @@ calculate_icers <- function(cost, effect, strategies, ref_str = NULL, wtp = NULL #' @return a string such as \code{"Dotted line: WTP = $50,000/QALY"}. #' @keywords internal wtp_caption <- function(wtp, currency, effect_units = "QALYs") { - unit <- sub("s$", "", effect_units) + unit <- per_unit(effect_units) paste0("Dotted line: WTP = ", currency, format(wtp, big.mark = ",", scientific = FALSE, trim = TRUE), "/", unit) } diff --git a/R/owsa.R b/R/owsa.R index 07a0c27..42c1bc1 100644 --- a/R/owsa.R +++ b/R/owsa.R @@ -82,7 +82,10 @@ owsa <- function(sa_obj, params = NULL, ranges = NULL, nsamp = 100, #' @param x an owsa object #' @param txtsize base text size in the plot #' @param col either full-color ("full") or black and white ("bw") -#' @param size either point size (ptype = "point") and/or line size (ptype = "line") +#' @param linewidth width of the lines. Defaults to 1. +#' @param xlim,ylim limits of the x (parameter values) and y (outcome) axes, applied to every +#' panel, or \code{NULL} (the default) to set them automatically. +#' @param size deprecated; use \code{linewidth} instead. #' @param facet_scales whether the x or y axes should be fixed. #' See \code{\link[ggplot2]{facet_grid}} in the \code{ggplo2} package for #' more details. @@ -105,11 +108,18 @@ plot.owsa <- function(x, txtsize = 12, facet_scales = c("free_x", "free_y", "free", "fixed"), facet_nrow = NULL, facet_ncol = NULL, - size = 1, + linewidth = 1, n_x_ticks = 6, n_y_ticks = 6, basecase = NULL, + xlim = NULL, + ylim = NULL, + size = deprecated(), ...) { + if (is_present(size)) { + deprecate_soft("1.1.0", "plot.owsa(size)", "plot.owsa(linewidth)") + linewidth <- size + } param_val <- outcome_val <- strategy <- NULL v_strategies <- unique(x$strategy) scales <- match.arg(facet_scales) @@ -123,12 +133,12 @@ plot.owsa <- function(x, txtsize = 12, if (col == "full" || col == "access") { owsa <- owsa + geom_line(aes(color = strategy), - linewidth = size) + linewidth = linewidth) } if (col == "bw") { owsa <- owsa + geom_line(aes(linetype = strategy), - linewidth = size) + + linewidth = linewidth) + scale_linetype_discrete(name = "Strategy") } @@ -153,6 +163,7 @@ plot.owsa <- function(x, txtsize = 12, scale_name = "Strategy", n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks, continuous = c("x", "y"), + xlim = xlim, ylim = ylim, v_str = v_strategies) } @@ -333,7 +344,8 @@ owsa_opt_strat <- function(owsa, params = NULL, maximize = TRUE, facet_ncol = 1, facet_nrow = NULL, facet_lab_txtsize = NULL, - n_x_ticks = 10) { + n_x_ticks = 10, + xlim = NULL) { # check that is owsa object if (!is_owsa(owsa)) { stop("must provide an owsa object created with owsa()") @@ -396,7 +408,7 @@ owsa_opt_strat <- function(owsa, params = NULL, maximize = TRUE, g <- add_common_aes(g, txtsize, scale_name = "Optimal Strategy: ", col, col_aes = "fill", continuous = "x", facet_lab_txtsize = facet_lab_txtsize, - n_x_ticks = n_x_ticks) + + n_x_ticks = n_x_ticks, xlim = xlim) + # these remove the meaningless y axis labels and text theme(axis.line.y = element_blank(), axis.text.y = element_blank(), diff --git a/R/twsa.R b/R/twsa.R index dda650b..1227b54 100644 --- a/R/twsa.R +++ b/R/twsa.R @@ -98,6 +98,8 @@ plot.twsa <- function(x, maximize = TRUE, n_y_ticks = 6, txtsize = 12, basecase = NULL, + xlim = NULL, + ylim = NULL, ...) { outcome_val <- strategy <- NULL @@ -142,6 +144,7 @@ plot.twsa <- function(x, maximize = TRUE, continuous = c("x", "y"), n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks, + xlim = xlim, ylim = ylim, xexpand = c(0, 0), yexpand = c(0, 0)) } diff --git a/man/ceac.Rd b/man/ceac.Rd index 31ade6a..2662651 100644 --- a/man/ceac.Rd +++ b/man/ceac.Rd @@ -4,12 +4,12 @@ \alias{ceac} \title{Cost-Effectiveness Acceptability Curve (CEAC)} \usage{ -ceac(wtp, psa) +ceac(psa, wtp) } \arguments{ -\item{wtp}{numeric vector with willingness-to-pay (WTP) thresholds} - \item{psa}{psa object from \code{\link{make_psa_obj}}} + +\item{wtp}{numeric vector with willingness-to-pay (WTP) thresholds} } \value{ An object of class \code{ceac} that can be visualized with \code{plot}. The \code{ceac} @@ -22,6 +22,10 @@ particular WTP is on the cost-efficient frontier. curves (CEAC) from a probabilistic sensitivity analysis (PSA) dataset. } \details{ +Like \code{\link{calc_exp_loss}} and \code{\link{calc_evpi}}, \code{ceac} takes the +\code{psa} object first. The order used before dampack 1.1.0, \code{ceac(wtp, psa)}, still +works but is deprecated; named arguments work in any order. + \code{ceac} computes the probability of each of the strategies being cost-effective at each \code{wtp} threshold. The returned object has classes \code{ceac} and \code{data.frame}, and has its own plot method (\code{\link{plot.ceac}}). @@ -36,7 +40,7 @@ psa_cancer <- make_psa_obj(cost = cancer_psa_data$cost, # define wtp threshold vector (can also use a single wtp) wtp <- seq(1e4, 1e5, by = 1e4) -ceac_obj <- ceac(wtp, psa_cancer) +ceac_obj <- ceac(psa_cancer, wtp) plot(ceac_obj) # see ?plot.ceac for options # this is most useful when there are many strategies diff --git a/man/owsa_opt_strat.Rd b/man/owsa_opt_strat.Rd index 77970a5..9ee511d 100644 --- a/man/owsa_opt_strat.Rd +++ b/man/owsa_opt_strat.Rd @@ -17,7 +17,8 @@ owsa_opt_strat( facet_ncol = 1, facet_nrow = NULL, facet_lab_txtsize = NULL, - n_x_ticks = 10 + n_x_ticks = 10, + xlim = NULL ) } \arguments{ @@ -48,6 +49,8 @@ changes in optimal strategy as they vary.} \item{facet_lab_txtsize}{text size for plot facet labels} \item{n_x_ticks}{number of x-axis ticks} + +\item{xlim}{vector of x-axis limits, or NULL, which sets limits automatically} } \value{ If \code{return == "plot"}, a \code{ggplot2} optimal strategy plot derived from the \code{owsa} diff --git a/man/per_unit.Rd b/man/per_unit.Rd new file mode 100644 index 0000000..10466c2 --- /dev/null +++ b/man/per_unit.Rd @@ -0,0 +1,19 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/add_common_aes.R +\name{per_unit} +\alias{per_unit} +\title{Singular form of the effect units, for "per unit" labels} +\usage{ +per_unit(effect_units) +} +\arguments{ +\item{effect_units}{units of effectiveness, such as \code{"QALYs"}.} +} +\value{ +a string. +} +\description{ +Drops a final "s", so \code{"QALYs"} becomes \code{"QALY"} in labels such as "$/QALY". A unit +already in the singular is returned unchanged. +} +\keyword{internal} diff --git a/man/plot.ceac.Rd b/man/plot.ceac.Rd index ff0e269..1b648e8 100644 --- a/man/plot.ceac.Rd +++ b/man/plot.ceac.Rd @@ -18,7 +18,7 @@ ylim = NULL, xlim = c(0, NA), col = c("access", "full", "bw"), - effect_units = "QALY", + effect_units = "QALYs", ... ) } @@ -56,7 +56,9 @@ will override \code{n_y_ticks} if provided.} \item{col}{either none, full color, accessible colors, or black and white} -\item{effect_units}{units of effectiveness, used in the x-axis label. Default: QALY} +\item{effect_units}{units of effectiveness, in the plural (for example \code{"QALYs"} or +\code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +("$/QALY"), and a value already in the singular is used as given.} \item{...}{further arguments to plot. This is not used by \code{dampack} but required for generic consistency.} diff --git a/man/plot.evpi.Rd b/man/plot.evpi.Rd index 1978b0f..49fc72d 100644 --- a/man/plot.evpi.Rd +++ b/man/plot.evpi.Rd @@ -8,7 +8,7 @@ x, txtsize = 12, currency = NULL, - effect_units = "QALY", + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -28,7 +28,9 @@ Default: the currency of the PSA the results were computed from (or $), but it could be any currency symbol or word (e.g., £, €, peso)} -\item{effect_units}{units of effectiveness. Default: QALY} +\item{effect_units}{units of effectiveness, in the plural (for example \code{"QALYs"} or +\code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +("$/QALY"), and a value already in the singular is used as given.} \item{n_y_ticks}{number of y-axis ticks} diff --git a/man/plot.evppi.Rd b/man/plot.evppi.Rd index 519e9df..5584a62 100644 --- a/man/plot.evppi.Rd +++ b/man/plot.evppi.Rd @@ -8,7 +8,7 @@ x, txtsize = 12, currency = NULL, - effect_units = "QALY", + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -28,7 +28,9 @@ Default: the currency of the PSA the results were computed from (or $), but it could be any currency symbol or word (e.g., £, €, peso)} -\item{effect_units}{units of effectiveness. Default: QALY} +\item{effect_units}{units of effectiveness, in the plural (for example \code{"QALYs"} or +\code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +("$/QALY"), and a value already in the singular is used as given.} \item{n_y_ticks}{number of y-axis ticks} diff --git a/man/plot.evsi.Rd b/man/plot.evsi.Rd index 0c9e858..0954135 100644 --- a/man/plot.evsi.Rd +++ b/man/plot.evsi.Rd @@ -8,7 +8,7 @@ x, txtsize = 12, currency = NULL, - effect_units = "QALY", + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -29,7 +29,9 @@ Default: the currency of the PSA the results were computed from (or $), but it could be any currency symbol or word (e.g., £, €, peso)} -\item{effect_units}{units of effectiveness. Default: QALY} +\item{effect_units}{units of effectiveness, in the plural (for example \code{"QALYs"} or +\code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +("$/QALY"), and a value already in the singular is used as given.} \item{n_y_ticks}{number of y-axis ticks} diff --git a/man/plot.exp_loss.Rd b/man/plot.exp_loss.Rd index 0d46626..29f21d7 100644 --- a/man/plot.exp_loss.Rd +++ b/man/plot.exp_loss.Rd @@ -9,10 +9,10 @@ log_y = TRUE, frontier = TRUE, points = TRUE, - lsize = 1, + linewidth = 1, txtsize = 12, currency = NULL, - effect_units = "QALY", + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -20,6 +20,7 @@ xlim = c(0, NA), ylim = NULL, col = c("access", "full", "bw"), + lsize = deprecated(), ... ) } @@ -34,7 +35,7 @@ To only plot the EVPI see \code{\link{calc_evpi}}.} \item{points}{whether to plot points on the curve (TRUE) or not (FALSE)} -\item{lsize}{line size. defaults to 1.} +\item{linewidth}{width of the lines. Defaults to 1.} \item{txtsize}{base text size} @@ -42,7 +43,9 @@ To only plot the EVPI see \code{\link{calc_evpi}}.} Default: the currency of the PSA the results were computed from (or $), but it could be any currency symbol or word (e.g., £, €, peso)} -\item{effect_units}{units of effectiveness. Default: QALY} +\item{effect_units}{units of effectiveness, in the plural (for example \code{"QALYs"} or +\code{"life-years"}). Default: \code{"QALYs"}. The willingness-to-pay axis uses the singular +("$/QALY"), and a value already in the singular is used as given.} \item{n_y_ticks}{number of y-axis ticks} @@ -60,6 +63,8 @@ will override \code{n_y_ticks} if provided.} \item{col}{either none, full color, accessible colors, or black and white} +\item{lsize}{deprecated; use \code{linewidth} instead.} + \item{...}{further arguments to plot. This is not used by \code{dampack} but required for generic consistency.} } diff --git a/man/plot.owsa.Rd b/man/plot.owsa.Rd index da9224b..1645918 100644 --- a/man/plot.owsa.Rd +++ b/man/plot.owsa.Rd @@ -11,10 +11,13 @@ facet_scales = c("free_x", "free_y", "free", "fixed"), facet_nrow = NULL, facet_ncol = NULL, - size = 1, + linewidth = 1, n_x_ticks = 6, n_y_ticks = 6, basecase = NULL, + xlim = NULL, + ylim = NULL, + size = deprecated(), ... ) } @@ -35,7 +38,7 @@ more details.} The default (NULL) is passed to \code{\link[ggplot2]{facet_wrap}}, which determines the number of rows and columns automatically.} -\item{size}{either point size (ptype = "point") and/or line size (ptype = "line")} +\item{linewidth}{width of the lines. Defaults to 1.} \item{n_x_ticks}{number of x-axis ticks} @@ -45,6 +48,11 @@ which determines the number of rows and columns automatically.} on the returned plot. Each list element must have the same name as the corresponding parameter in the \code{owsa} object.} +\item{xlim, ylim}{limits of the x (parameter values) and y (outcome) axes, applied to every +panel, or \code{NULL} (the default) to set them automatically.} + +\item{size}{deprecated; use \code{linewidth} instead.} + \item{...}{further arguments to plot. This is not used by \code{dampack} but required for generic consistency.} } diff --git a/man/plot.twsa.Rd b/man/plot.twsa.Rd index 725df6b..7693230 100644 --- a/man/plot.twsa.Rd +++ b/man/plot.twsa.Rd @@ -12,6 +12,8 @@ n_y_ticks = 6, txtsize = 12, basecase = NULL, + xlim = NULL, + ylim = NULL, ... ) } @@ -33,6 +35,10 @@ on the returned plot. Each list element must have the same name as the corresponding parameter in the \code{owsa} object.} +\item{xlim}{vector of x-axis limits, or NULL, which sets limits automatically} + +\item{ylim}{vector of y-axis limits, or NULL, which sets limits automatically} + \item{...}{further arguments to plot. This is not used by \code{dampack} but required for generic consistency.} } diff --git a/tests/testthat/test_api_harmonize.R b/tests/testthat/test_api_harmonize.R new file mode 100644 index 0000000..e461072 --- /dev/null +++ b/tests/testthat/test_api_harmonize.R @@ -0,0 +1,68 @@ +# Harmonized arguments across the analysis and plot functions (#214). Old call forms keep +# working, with a soft deprecation warning. + +data("cancer_psa_data") +psa_big <- make_psa_obj(cancer_psa_data$cost, cancer_psa_data$effectiveness, + cancer_psa_data$parameters, cancer_psa_data$strategies) +v_wtp <- seq(1e4, 1e5, by = 3e4) + +test_that("ceac() takes psa first; the old (wtp, psa) order still works, deprecated", { + df_new <- ceac(psa_big, v_wtp) + expect_s3_class(df_new, "ceac") + # named arguments work in either order, without a warning + expect_no_warning(df_named <- ceac(wtp = v_wtp, psa = psa_big)) + expect_identical(df_named, df_new) + # the old positional order gives the same result and one deprecation warning + lifecycle::expect_deprecated(df_old <- ceac(v_wtp, psa_big), "must come after `psa`") + expect_identical(df_old, df_new) + # a non-psa first argument still gets the usual error + expect_error(ceac(v_wtp, v_wtp), "class `psa`") +}) + +test_that("plot.owsa() and plot.exp_loss() take linewidth; size and lsize are deprecated", { + o <- owsa(psa_big, outcome = "eff") + line_width <- function(p) { + i <- which(vapply(p$layers, function(l) inherits(l$geom, "GeomLine"), logical(1)))[1] + unique(ggplot2::layer_data(p, i)$linewidth) + } + expect_equal(line_width(plot(o, linewidth = 2)), 2) + lifecycle::expect_deprecated(p_old <- plot(o, size = 2), "linewidth") + expect_equal(line_width(p_old), 2) + + el <- calc_exp_loss(psa_big, v_wtp) + expect_equal(line_width(plot(el, linewidth = 2)), 2) + lifecycle::expect_deprecated(p_old <- plot(el, lsize = 2), "linewidth") + expect_equal(line_width(p_old), 2) +}) + +test_that("plot.owsa(), plot.twsa() and owsa_opt_strat() accept axis limits", { + scale_limits <- function(p, aes) p$scales$get_scales(aes)$limits + o <- owsa(psa_big, outcome = "eff") + p <- plot(o, xlim = c(0, 1), ylim = c(5, 15)) + expect_equal(scale_limits(p, "x"), c(0, 1)) + expect_equal(scale_limits(p, "y"), c(5, 15)) + expect_null(scale_limits(plot(o), "x")) + + tw <- twsa(psa_big, "pFailChemo", "muDieCancer", outcome = "eff") + p <- plot(tw, xlim = c(0.3, 0.6), ylim = c(0.05, 0.2)) + expect_equal(scale_limits(p, "x"), c(0.3, 0.6)) + expect_equal(scale_limits(p, "y"), c(0.05, 0.2)) + + o_nmb <- owsa(psa_big, outcome = "nmb", wtp = 1e5) + p <- owsa_opt_strat(o_nmb, xlim = c(0, 1)) + expect_equal(scale_limits(p, "x"), c(0, 1)) +}) + +test_that("effect_units defaults to QALYs everywhere, singular in per-unit labels", { + # the default labels are unchanged: "$/QALY" on willingness-to-pay axes + expect_match(plot(ceac(psa_big, v_wtp))$labels$x, "Thousand $ / QALY)", fixed = TRUE) + expect_match(plot(calc_exp_loss(psa_big, v_wtp))$labels$x, "Thousand $/QALY)", fixed = TRUE) + expect_match(plot(calc_evpi(psa_big, v_wtp))$labels$x, "Thousand $/QALY)", fixed = TRUE) + # plural units are made singular there; units already in the singular are kept + expect_match(plot(calc_evpi(psa_big, v_wtp), effect_units = "life-years")$labels$x, + "$/life-year)", fixed = TRUE) + expect_match(plot(calc_evpi(psa_big, v_wtp), effect_units = "QALY")$labels$x, + "$/QALY)", fixed = TRUE) + expect_equal(per_unit(c("QALYs", "QALY", "life-years", "DALYs averted")), + c("QALY", "QALY", "life-year", "DALYs averted")) +}) diff --git a/tests/testthat/test_ceac.R b/tests/testthat/test_ceac.R index 3a03f6d..2a0787d 100644 --- a/tests/testthat/test_ceac.R +++ b/tests/testthat/test_ceac.R @@ -18,7 +18,7 @@ psa_obj <- make_psa_obj(cancer_psa_data$cost, cancer_psa_data$strategies) test_that("result has class 'ceac'", { - c <- ceac(wtp, psa_obj) + c <- ceac(psa_obj, wtp) expect_true(inherits(c, "data.frame")) expect_true(inherits(c, "ceac")) }) @@ -27,7 +27,7 @@ test_that("handles missing strategy", { psa_missing <- make_psa_obj(cancer_psa_data$cost, cancer_psa_data$effectiveness, cancer_psa_data$parameters) - c_missing <- ceac(wtp, psa_missing) + c_missing <- ceac(psa_missing, wtp) expected_generic_strat <- factor(c("Strategy_1", "Strategy_2", "Strategy_3"), ordered = TRUE) obtained_generic_strat <- sort(unique(c_missing$Strategy)) expect_equal(expected_generic_strat, obtained_generic_strat) @@ -38,7 +38,7 @@ test_that("handles missing strategy", { ## summary test_that("message is correct in summary.ceac", { - c <- ceac(wtp, psa_obj) + c <- ceac(psa_obj, wtp) df_sum <- summary(c) expect_equal(df_sum$optimal_strategy, c("Radio", "Chemo")) }) @@ -65,7 +65,7 @@ test_that("summary.ceac summarizes a real psa whose frontier switches many times data("df_example_psa_elc") l_psa <- make_psa_obj(cost = df_example_psa_elc[, 1:6], effectiveness = df_example_psa_elc[, 7:12]) - df_ceac <- ceac(seq(1000, 150000, 1000), l_psa) + df_ceac <- ceac(l_psa, seq(1000, 150000, 1000)) df_sum <- summary(df_ceac) # expected intervals derived independently, by run-length encoding the frontier @@ -83,7 +83,7 @@ test_that("summary.ceac summarizes a real psa whose frontier switches many times ## plot test_that("plot.ceac produces ggplot object", { - ceac_obj <- ceac(wtp, psa_obj) + ceac_obj <- ceac(psa_obj, wtp) gf <- plot(ceac_obj, frontier = TRUE) expect_s3_class(gf, "ggplot") @@ -107,7 +107,7 @@ test_that("near-tied strategies are not chosen at random (#167)", { psa_tie <- make_psa_obj(df_c, df_e, strategies = c("A", "B")) for (seed in 1:3) { set.seed(seed) - df_ceac <- ceac(1e5, psa_tie) + df_ceac <- ceac(psa_tie, 1e5) expect_equal(df_ceac$Proportion[df_ceac$Strategy == "B"], 1) expect_equal(calc_evpi(psa_tie, 1e5)$EVPI, 0) df_elc <- calc_exp_loss(psa_tie, 1e5) @@ -120,7 +120,7 @@ test_that("exact ties are broken deterministically, in favor of the first strate psa_same <- make_psa_obj(df_same, df_same, strategies = c("A", "B")) v_prop <- vapply(1:5, function(seed) { set.seed(seed) - df_ceac <- ceac(100, psa_same) + df_ceac <- ceac(psa_same, 100) df_ceac$Proportion[df_ceac$Strategy == "A"] }, numeric(1)) expect_equal(v_prop, rep(1, 5)) diff --git a/tests/testthat/test_currency.R b/tests/testthat/test_currency.R index fbc3e12..ef984d0 100644 --- a/tests/testthat/test_currency.R +++ b/tests/testthat/test_currency.R @@ -10,7 +10,7 @@ v_wtp <- seq(10000, 100000, by = 30000) eur <- "€" test_that("ceac() and calc_exp_loss() keep the currency and use it in their plots", { - df_ceac <- ceac(v_wtp, psa_eur) + df_ceac <- ceac(psa_eur, v_wtp) expect_identical(attr(df_ceac, "currency"), eur) expect_match(plot(df_ceac)$labels$x, eur, fixed = TRUE) expect_match(plot(df_ceac, currency = "£")$labels$x, "£", fixed = TRUE) @@ -29,11 +29,11 @@ test_that("EVPI, EVPPI, and EVSI plots use the currency or the health units of t evppi_nmb <- calc_evppi(psa_eur, v_wtp, params = "pFailChemo", outcome = "nmb", progress = FALSE) expect_equal(plot(evppi_nmb)$labels$y, paste0("EVPPI (", eur, ")")) evppi_nhb <- calc_evppi(psa_eur, v_wtp, params = "pFailChemo", outcome = "nhb", progress = FALSE) - expect_equal(plot(evppi_nhb)$labels$y, "EVPPI (QALY)") + expect_equal(plot(evppi_nhb)$labels$y, "EVPPI (QALYs)") # calc_evsi() defaults to outcome = "nhb", whose EVSI is in health units, not currency evsi_nhb <- calc_evsi(psa_eur, v_wtp, params = "pFailChemo", n = 100, n0 = 10, progress = FALSE) - expect_equal(plot(evsi_nhb)$labels$y, "EVSI (QALY)") + expect_equal(plot(evsi_nhb)$labels$y, "EVSI (QALYs)") evsi_nmb <- calc_evsi(psa_eur, v_wtp, params = "pFailChemo", n = 100, n0 = 10, outcome = "nmb", progress = FALSE) expect_equal(plot(evsi_nmb)$labels$y, paste0("EVSI (", eur, ")")) @@ -49,6 +49,6 @@ test_that("calculate_icers_psa() keeps the currency for print and plot", { }) test_that("a dollar psa object still gives dollar labels", { - expect_match(plot(ceac(v_wtp, psa_usd))$labels$x, "$", fixed = TRUE) + expect_match(plot(ceac(psa_usd, v_wtp))$labels$x, "$", fixed = TRUE) expect_equal(plot(calc_evpi(psa_usd, v_wtp))$labels$y, "EVPI ($)") }) diff --git a/tests/testthat/test_elc.R b/tests/testthat/test_elc.R index 0b8289e..cd0eeb1 100644 --- a/tests/testthat/test_elc.R +++ b/tests/testthat/test_elc.R @@ -60,9 +60,9 @@ test_that("plot.exp_loss runs with several combinations of arguments", { }) # black-and-white expected loss curves ignored lsize and warned about an unused color scale (#210) -test_that("plot.exp_loss(col = 'bw') uses lsize and builds without warnings", { +test_that("plot.exp_loss(col = 'bw') uses linewidth and builds without warnings", { el <- calc_exp_loss(psa_obj, wtp = seq(1e4, 1e5, 1e4)) - g <- plot(el, col = "bw", lsize = 3) + g <- plot(el, col = "bw", linewidth = 3) expect_warning(b <- ggplot2::ggplot_build(g), NA) i_line <- which(vapply(g$layers, function(l) inherits(l$geom, "GeomLine"), logical(1))) expect_equal(unique(b$data[[i_line]]$linewidth), 3) diff --git a/tests/testthat/test_plot_options.R b/tests/testthat/test_plot_options.R index e639464..6ce3691 100644 --- a/tests/testthat/test_plot_options.R +++ b/tests/testthat/test_plot_options.R @@ -41,7 +41,7 @@ test_that("plot.psa() without center points builds without a fill-scale warning" }) test_that("plot.ceac(): frontier, points, and min_prob", { - df_ceac <- ceac(v_wtp, psa_big) + df_ceac <- ceac(psa_big, v_wtp) expect_true("GeomPoint" %in% geoms(plot(df_ceac))) p_plain <- plot(df_ceac, frontier = FALSE, points = FALSE) expect_false("GeomPoint" %in% geoms(p_plain)) diff --git a/tests/testthat/test_strategy_names.R b/tests/testthat/test_strategy_names.R index 9949c4b..cc00c4c 100644 --- a/tests/testthat/test_strategy_names.R +++ b/tests/testthat/test_strategy_names.R @@ -29,7 +29,7 @@ test_that("ICERs, CEAC, expected loss, and EVPI keep the names", { df_icers <- calculate_icers(df_sum$meanCost, df_sum$meanEffect, df_sum$Strategy) expect_setequal(df_icers$Strategy, v_names) - df_ceac <- ceac(v_wtp, l_psa) + df_ceac <- ceac(l_psa, v_wtp) expect_setequal(as.character(unique(df_ceac$Strategy)), v_names) expect_true(all(summary(df_ceac)$optimal_strategy %in% v_names)) @@ -59,7 +59,7 @@ test_that("metamodel-based analyses work with non-syntactic names", { test_that("plot legends show the names exactly as typed", { l_psa <- make_named_psa() expect_setequal(guide_labels(plot(l_psa)), v_names) - expect_setequal(guide_labels(plot(ceac(v_wtp, l_psa))), v_names) + expect_setequal(guide_labels(plot(ceac(l_psa, v_wtp))), v_names) expect_setequal(guide_labels(plot(calc_exp_loss(l_psa, v_wtp))), v_names) df_owsa <- owsa(l_psa, params = "pFailChemo", outcome = "nmb", wtp = 50000) expect_setequal(guide_labels(plot(df_owsa)), v_names) From 0d6af8e87568146ec6fb5706c12e81b2cf85ef3a Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Fri, 13 Nov 2026 17:39:05 -0800 Subject: [PATCH 09/10] Require lifecycle (>= 1.0.3): ggplot2 3.5.0 needs lifecycle > 1.0.1 The minimum-dependency CI job could not install ggplot2@3.5.0 with lifecycle@1.0.0. --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index fbd1e15..47d080c 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -59,7 +59,7 @@ Imports: triangle, ggrepel, tidyr, - lifecycle (>= 1.0.0), + lifecycle (>= 1.0.3), rlang, viridis, RColorBrewer From b7d53e914945dad821e86b88227c09b882d7de1d Mon Sep 17 00:00:00 2001 From: Fernando Alarid-Escudero Date: Fri, 13 Nov 2026 17:45:13 -0800 Subject: [PATCH 10/10] List lifecycle without a version bound Current dplyr needs lifecycle (>= 1.0.5) and ggplot2 3.5.0 needs lifecycle (> 1.0.1), so any lower pin makes the minimum-dependency environment unsolvable. dampack only uses deprecate_soft(), deprecated() and is_present(), which predate lifecycle 1.0. --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 47d080c..fad7bb3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -59,7 +59,7 @@ Imports: triangle, ggrepel, tidyr, - lifecycle (>= 1.0.3), + lifecycle, rlang, viridis, RColorBrewer