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 03eb033..b90d60a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -59,6 +59,7 @@ Imports: triangle, ggrepel, tidyr, + lifecycle, rlang, viridis, RColorBrewer diff --git a/NAMESPACE b/NAMESPACE index 7958a75..1dca31c 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,6 +1,7 @@ # Generated by roxygen2: do not edit by hand S3method(plot,ceac) +S3method(plot,cers_ref) S3method(plot,evpi) S3method(plot,evppi) S3method(plot,evsi) @@ -10,6 +11,7 @@ S3method(plot,owsa) S3method(plot,psa) S3method(plot,twsa) S3method(predict,metamodel) +S3method(print,cers_ref) S3method(print,icers) S3method(print,metamodel) S3method(print,sa) @@ -21,6 +23,8 @@ export(calc_evpi) export(calc_evppi) export(calc_evsi) export(calc_exp_loss) +export(calculate_cers_ref) +export(calculate_cers_ref_psa) export(calculate_icers) export(calculate_icers_psa) export(ceac) @@ -46,6 +50,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 69ce9ba..9d802f2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,13 @@ ## 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). +- 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). +- New `calculate_cers_ref()` and `calculate_cers_ref_psa()` compare every strategy with a reference strategy chosen by the user, such as the standard of care: the difference in cost and effect from the reference, the cost-effectiveness ratio (CER) of that difference, and the status relative to the reference ("Dominant", "Dominated", "More costly, more effective", "Less costly, less effective", or "Equivalent"). With `wtp`, they add the net monetary benefit and its difference from the reference. From a PSA, `uncertainty = TRUE` adds 95% intervals for the differences and the proportion of samples in each quadrant of the incremental cost-effectiveness plane and, with `wtp`, the proportion that is cost-effective compared with the reference. `plot()` draws the incremental plane centered at the reference, with a segment to each strategy and an optional willingness-to-pay line. These comparisons complement, and do not replace, the fully incremental analysis of `calculate_icers()`, which HTA guidelines require; the documentation cites the NICE, CDA-AMC, and Zorginstituut Nederland guidelines (#209). +- `plot.icers()` gains `incremental = TRUE`, which plots the incremental cost-effectiveness plane with the first non-dominated strategy (the least costly strategy on the frontier) at the origin, and `wtp`, which draws a willingness-to-pay line through that strategy. `plot.psa()` gains `wtp` for the same line, drawn through the reference strategy or, without one, through the least costly strategy (#209, #202). +- `calculate_icers()` and `calculate_icers_psa()` gain `wtp`, which adds the net monetary benefit (`NMB`) of each strategy, and `nhb = TRUE`, which also adds the net health benefit (`NHB`) (#200). +- `calculate_icers()` gains `currency`, which `print.icers()` and `plot.icers()` use (#203). - `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"`. @@ -11,6 +18,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 @@ -22,6 +31,8 @@ ## 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.exp_loss()` with its default log-scale y axis (`log_y = TRUE`) now labels every order of magnitude. Its evenly spaced default breaks used to bunch up at the top of the log axis and leave the lower curves without any labels. - The `hund_strat` help page now describes the data (simulated costs and QALYs for 100 hypothetical strategies) and its columns, with an example. Typos in several help pages are fixed (#219). - `plot.psa(center = FALSE)` no longer warns "No shared levels found between `names(values)` of the manual scale and the data's fill values" when it is drawn. The fill scale is now added only when the center points that use it are. diff --git a/R/add_common_aes.R b/R/add_common_aes.R index 7da2e95..c26b626 100644 --- a/R/add_common_aes.R +++ b/R/add_common_aes.R @@ -252,3 +252,42 @@ 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 +} + +#' 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 b4a5621..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) @@ -124,6 +137,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 } @@ -136,7 +150,11 @@ 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, 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 @@ -159,7 +177,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, @@ -169,7 +187,9 @@ plot.ceac <- function(x, ylim = NULL, xlim = c(0, NA), col = c("access", "full", "bw"), + effect_units = "QALYs", ...) { + currency <- resolve_currency(currency, x) wtp_name <- "WTP" prop_name <- "Proportion" strat_name <- "Strategy" @@ -219,7 +239,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, " / ", per_unit(effect_units), ")", sep = "")) + ylab("Pr Most Cost-Effective") if (points) { diff --git a/R/cers_ref.R b/R/cers_ref.R new file mode 100644 index 0000000..c26d5e0 --- /dev/null +++ b/R/cers_ref.R @@ -0,0 +1,481 @@ +# nolint start: line_length_linter. (guideline URL in the references) +#' Compare every strategy with a reference strategy +#' +#' @description +#' Compares each strategy with a single reference strategy chosen by the user, such as the +#' current standard of care: the difference in cost and in effect from the reference, the +#' cost-effectiveness ratio (CER) of that difference, and where each strategy lies on the +#' incremental cost-effectiveness plane centered at the reference. +#' +#' These comparisons are \emph{not} the incremental cost-effectiveness ratios (ICERs) of a +#' fully incremental analysis. When more than two strategies are compared, health technology +#' assessment guidelines require a fully incremental (sequential) analysis, in which dominated +#' and extendedly dominated strategies are removed and each strategy on the cost-effectiveness +#' frontier is compared with the next less costly one: use \code{\link{calculate_icers}} for that. +#' Comparisons with a single reference are a complement for settings where they are relevant +#' and justified. The NICE manual (2022), for example, states that "pairwise comparisons may be +#' presented when relevant and justified (for example, when the technology is expected to +#' specifically displace individual comparators)", after requiring a fully incremental +#' analysis. The CDA-AMC (2017) and Zorginstituut Nederland (2024) guidelines also require a +#' sequential analysis when more than two interventions are compared. +#' +#' @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 the reference strategy, one of \code{strategies}, for example +#' \code{"Standard of care"}. +#' @param wtp a single willingness-to-pay threshold (currency per unit of effect). If given, the +#' net monetary benefit of each strategy and its difference from the reference are added. +#' The default (\code{NULL}) adds no net-benefit columns. +#' @param nhb if \code{TRUE}, also add the net health benefit and its difference from the +#' reference. 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 of class \code{cers_ref}, with the reference strategy in the first row +#' and the other strategies by increasing cost, and these columns: +#' \describe{ +#' \item{Strategy, Cost, Effect}{as given.} +#' \item{Inc_Cost, Inc_Effect}{cost and effect minus those of the reference.} +#' \item{CER}{\code{Inc_Cost / Inc_Effect}, the cost-effectiveness ratio compared with the +#' reference. It is \code{NA} where a ratio is not meaningful: for the reference itself and for +#' dominant, dominated and equivalent strategies.} +#' \item{Status}{one of \code{"Reference"}, \code{"Dominant"} (not more costly and at least as +#' effective), \code{"Dominated"} (not less costly and no more effective), +#' \code{"More costly, more effective"}, \code{"Less costly, less effective"}, or +#' \code{"Equivalent"} (same cost and effect).} +#' \item{NMB, Inc_NMB}{with \code{wtp}: the net monetary benefit, \code{wtp * Effect - Cost}, +#' and its difference from the reference. A strategy with a positive \code{Inc_NMB} is +#' cost-effective compared with the reference at this threshold.} +#' \item{NHB, Inc_NHB}{with \code{nhb = TRUE}: the net health benefit, +#' \code{Effect - Cost / wtp}, and its difference from the reference.} +#' } +#' The reference strategy, threshold and currency are stored as attributes, which the +#' \code{print} and \code{plot} methods use. +#' +#' For a strategy that is more costly and more effective than the reference, a \code{CER} below +#' the willingness-to-pay threshold means it is cost-effective compared with the reference. For a +#' strategy that is less costly and less effective, the \code{CER} is the cost saved per unit of +#' effect lost, and the strategy is cost-effective compared with the reference when its +#' \code{CER} is \emph{above} the threshold. +#' +#' @references +#' National Institute for Health and Care Excellence (NICE). NICE health technology evaluations: +#' the manual (PMG36), section 4.6, "Economic evaluation". London: NICE; 2022. +#' \url{https://www.nice.org.uk/process/pmg36/chapter/economic-evaluation-2} +#' +#' CDA-AMC (formerly CADTH). Guidelines for the Economic Evaluation of Health Technologies: +#' Canada. 4th ed. Ottawa: CADTH; 2017. +#' \url{https://www.cda-amc.ca/sites/default/files/pdf/guidelines_for_the_economic_evaluation_of_health_technologies_canada_4th_ed.pdf} +#' +#' Zorginstituut Nederland. Guideline for economic evaluations in healthcare (2024 version). +#' Diemen: Zorginstituut Nederland; 2024. +#' \url{https://english.zorginstituutnederland.nl/documents/2024/01/16/guideline-for-economic-evaluations-in-healthcare} +#' +#' @seealso \code{\link{plot.cers_ref}}, \code{\link{calculate_cers_ref_psa}} for the same +#' comparison from a PSA, and \code{\link{calculate_icers}} for the fully incremental analysis. +#' +#' @examples +#' # three strategies; "Standard of care" is neither the cheapest nor the least effective +#' df_ref <- calculate_cers_ref(cost = c(12000, 9000, 20000), +#' effect = c(8.0, 7.6, 8.5), +#' strategies = c("Standard of care", "Generic drug", "New drug"), +#' ref_str = "Standard of care", +#' wtp = 50000) +#' df_ref +#' plot(df_ref) +#' +#' # the fully incremental analysis of the same strategies +#' calculate_icers(cost = c(12000, 9000, 20000), +#' effect = c(8.0, 7.6, 8.5), +#' strategies = c("Standard of care", "Generic drug", "New drug")) +#' @export +calculate_cers_ref <- function(cost, effect, strategies, ref_str, wtp = NULL, nhb = FALSE, + currency = NULL) { + if (length(cost) != length(effect) || length(effect) != length(strategies)) { + stop("cost, effect, and strategies must all be vectors of the same length", call. = FALSE) + } + if (length(strategies) == 0) { + stop("cost, effect, and strategies must contain at least one strategy", call. = FALSE) + } + if (missing(ref_str) || is.null(ref_str)) { + stop("`ref_str` must name the reference strategy.", call. = FALSE) + } + v_strat <- as.character(strategies) + if (anyDuplicated(v_strat)) { + stop("Strategy names must be unique.", call. = FALSE) + } + ref_str <- check_ref_str(ref_str, v_strat) + check_wtp_nhb(wtp, nhb) + + # reference first, then the other strategies by increasing cost (and decreasing effect) + v_order <- order(v_strat != ref_str, cost, -effect) + df_ref <- data.frame(Strategy = v_strat[v_order], Cost = cost[v_order], + Effect = effect[v_order], stringsAsFactors = FALSE) + is_ref <- df_ref$Strategy == ref_str + + # differences from the reference; its own are reported as NA + df_ref$Inc_Cost <- df_ref$Cost - df_ref$Cost[is_ref] + df_ref$Inc_Effect <- df_ref$Effect - df_ref$Effect[is_ref] + v_status <- status_vs_reference(df_ref$Inc_Cost, df_ref$Inc_Effect) + v_status[is_ref] <- "Reference" + df_ref$Inc_Cost[is_ref] <- NA_real_ + df_ref$Inc_Effect[is_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 the CER stays NA + v_has_ratio <- v_status %in% c("More costly, more effective", "Less costly, less effective") + df_ref$CER <- ifelse(v_has_ratio, df_ref$Inc_Cost / df_ref$Inc_Effect, NA_real_) + df_ref$Status <- v_status + + if (!is.null(wtp)) { + df_ref$NMB <- wtp * df_ref$Effect - df_ref$Cost + df_ref$Inc_NMB <- df_ref$NMB - df_ref$NMB[is_ref] + df_ref$Inc_NMB[is_ref] <- NA_real_ + if (nhb) { + df_ref$NHB <- df_ref$Effect - df_ref$Cost / wtp + df_ref$Inc_NHB <- df_ref$NHB - df_ref$NHB[is_ref] + df_ref$Inc_NHB[is_ref] <- NA_real_ + } + } + + structure(df_ref, class = c("cers_ref", "data.frame"), ref_str = ref_str, wtp = wtp, + currency = currency) +} + +# nolint end + +#' Compare every strategy with a reference strategy, from a \code{psa} object +#' +#' @description +#' Compares each strategy with a reference strategy using the mean costs and effects of a +#' probabilistic sensitivity analysis (PSA), as \code{\link{calculate_cers_ref}} does for a base +#' case. With \code{uncertainty = TRUE}, it also summarizes the uncertainty in each comparison +#' across the PSA samples. See \code{\link{calculate_cers_ref}} for when a comparison with a +#' single reference is appropriate, and \code{\link{calculate_icers_psa}} for the fully +#' incremental analysis. +#' +#' @param psa \code{psa} object from \code{\link{make_psa_obj}}. +#' @param uncertainty if \code{TRUE}, add the 95\% intervals and quadrant proportions described +#' in Value. Defaults to \code{FALSE}. +#' @inheritParams calculate_cers_ref +#' +#' @return A \code{cers_ref} object with the columns described in +#' \code{\link{calculate_cers_ref}}, computed from the mean cost and effect of each strategy. The +#' currency of \code{psa} is kept. +#' +#' With \code{uncertainty = TRUE}, the differences from the reference are computed in every PSA +#' sample, and these columns are added (\code{NA} for the reference itself): +#' \itemize{ +#' \item \code{Lower_95_Inc_Cost} and \code{Upper_95_Inc_Cost}, the 2.5th and 97.5th +#' percentiles of the difference in cost, placed after \code{Inc_Cost}; likewise for +#' \code{Inc_Effect} and, with \code{wtp}, \code{Inc_NMB} (and \code{Inc_NHB}). +#' \item \code{Prop_NE}, \code{Prop_SE}, \code{Prop_SW}, and \code{Prop_NW}, 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; SW not more effective and not more +#' costly; NW not more effective and more costly. The four proportions sum to 1. +#' \item With \code{wtp}, \code{Prop_CE}, the proportion of samples in which the strategy is +#' cost-effective compared with the reference (it has a higher net monetary benefit). +#' } +#' +#' @inherit calculate_cers_ref references +#' @seealso \code{\link{calculate_cers_ref}}, \code{\link{plot.cers_ref}}, and +#' \code{\link{plot.psa}} with \code{ref_str} for the PSA samples on the incremental plane. +#' +#' @examples +#' data(cancer_psa_data) +#' l_psa <- make_psa_obj(cost = cancer_psa_data$cost, +#' effectiveness = cancer_psa_data$effectiveness, +#' parameters = cancer_psa_data$parameters, +#' strategies = cancer_psa_data$strategies) +#' df_ref <- calculate_cers_ref_psa(l_psa, ref_str = "Radio", wtp = 50000, +#' uncertainty = TRUE) +#' df_ref +#' plot(df_ref) +#' @export +calculate_cers_ref_psa <- function(psa, ref_str, wtp = NULL, nhb = FALSE, uncertainty = FALSE) { + check_psa_object(psa) + if (!isTRUE(uncertainty) && !isFALSE(uncertainty)) { + stop("`uncertainty` must be TRUE or FALSE.", call. = FALSE) + } + df_sum <- summary(psa) + df_ref <- calculate_cers_ref(cost = df_sum$meanCost, effect = df_sum$meanEffect, + strategies = df_sum$Strategy, ref_str = ref_str, wtp = wtp, + nhb = nhb, currency = psa$currency) + if (uncertainty) { + df_ref <- add_cers_ref_uncertainty(df_ref, psa, wtp, nhb) + } + df_ref +} + +#' Add PSA intervals and quadrant proportions to a \code{cers_ref} object +#' +#' @param df_ref a \code{cers_ref} object computed from the means of \code{psa}. +#' @param psa the \code{psa} object. +#' @inheritParams calculate_cers_ref +#' @return \code{df_ref} with the columns described in \code{\link{calculate_cers_ref_psa}}. +#' @keywords internal +add_cers_ref_uncertainty <- function(df_ref, psa, wtp, nhb) { + ref_str <- attr(df_ref, "ref_str") + v_strat <- df_ref$Strategy + is_ref <- v_strat == ref_str + # sample-by-sample differences from the reference: one row per PSA sample, one column per + # strategy in the row order of df_ref (subtracting a vector recycles it down each column) + m_inc_cost <- as.matrix(psa$cost)[, v_strat, drop = FALSE] - psa$cost[[ref_str]] + m_inc_effect <- as.matrix(psa$effectiveness)[, v_strat, drop = FALSE] - + psa$effectiveness[[ref_str]] + l_inc <- list(Inc_Cost = m_inc_cost, Inc_Effect = m_inc_effect) + if (!is.null(wtp)) { + m_inc_nmb <- wtp * m_inc_effect - m_inc_cost + l_inc$Inc_NMB <- m_inc_nmb + if (nhb) { + l_inc$Inc_NHB <- m_inc_effect - m_inc_cost / wtp + } + } + na_ref <- function(v) { + v <- unname(v) + v[is_ref] <- NA_real_ + v + } + + # 95% intervals, each placed right after its point estimate + v_cols <- names(df_ref) + for (col in names(l_inc)) { + df_ref[[paste0("Lower_95_", col)]] <- na_ref(apply(l_inc[[col]], 2, quantile, probs = 0.025, + names = FALSE)) + df_ref[[paste0("Upper_95_", col)]] <- na_ref(apply(l_inc[[col]], 2, quantile, probs = 0.975, + names = FALSE)) + v_cols <- append(v_cols, paste0(c("Lower_95_", "Upper_95_"), col), after = match(col, v_cols)) + } + + # share of samples in each quadrant of the incremental plane, and cost-effective ones + df_ref$Prop_NE <- na_ref(colMeans(m_inc_effect > 0 & m_inc_cost > 0)) + df_ref$Prop_SE <- na_ref(colMeans(m_inc_effect > 0 & m_inc_cost <= 0)) + df_ref$Prop_SW <- na_ref(colMeans(m_inc_effect <= 0 & m_inc_cost <= 0)) + df_ref$Prop_NW <- na_ref(colMeans(m_inc_effect <= 0 & m_inc_cost > 0)) + v_cols <- c(v_cols, "Prop_NE", "Prop_SE", "Prop_SW", "Prop_NW") + if (!is.null(wtp)) { + df_ref$Prop_CE <- na_ref(colMeans(m_inc_nmb > 0)) + v_cols <- c(v_cols, "Prop_CE") + } + + l_attr <- attributes(df_ref)[c("class", "ref_str", "wtp", "currency")] + df_ref <- as.data.frame(unclass(df_ref)[v_cols], check.names = FALSE, stringsAsFactors = FALSE) + for (a in names(l_attr)) { + attr(df_ref, a) <- l_attr[[a]] + } + df_ref +} + +#' 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 +} + +#' 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")))) +} + +#' Print a comparison with a reference strategy +#' +#' Prints the table of a \code{\link{calculate_cers_ref}} object with formatted numbers and +#' headers that name the reference strategy. +#' +#' @param x a \code{cers_ref} object. +#' @param currency currency symbol. Defaults to the currency stored in \code{x}, or \code{"$"}. +#' @param dig_cost number of digits to round costs and net monetary benefits to. +#' @param dig_eff number of digits to round effects and net health benefits to. +#' @param dig_cer number of digits to round the cost-effectiveness ratios to. +#' @param dig_prop number of digits to round the proportions of PSA samples to. +#' @param ... further arguments (not used). +#' @return the formatted table, invisibly. +#' @export +print.cers_ref <- function(x, currency = NULL, dig_cost = 0, dig_eff = 2, dig_cer = 0, + dig_prop = 3, ...) { + currency <- resolve_currency(currency, x) + vs <- paste0(" vs ", attr(x, "ref_str")) + cat("Comparison of each strategy with the reference strategy, ", attr(x, "ref_str"), + "\n(not a fully incremental analysis; see calculate_icers())\n\n", sep = "") + df_table <- as.data.frame(unclass(x), check.names = FALSE, stringsAsFactors = FALSE) + l_format <- list( + Cost = list(dig_cost, paste0("Costs (", currency, ")")), + Effect = list(dig_eff, "QALYs"), + Inc_Cost = list(dig_cost, paste0("Incremental Costs", vs, " (", currency, ")")), + Inc_Effect = list(dig_eff, paste0("Incremental QALYs", vs)), + CER = list(dig_cer, paste0("CER", vs, " (", currency, "/QALY)")), + Status = list(NA, paste0("Status", vs)), + NMB = list(dig_cost, paste0("NMB (", currency, ")")), + Inc_NMB = list(dig_cost, paste0("Incremental NMB", vs, " (", currency, ")")), + NHB = list(dig_eff, "NHB (QALYs)"), + Inc_NHB = list(dig_eff, paste0("Incremental NHB", vs, " (QALYs)")) + ) + # interval columns use the digits of their point estimate; proportions their own + for (col in grep("^(Lower|Upper)_95_", names(df_table), value = TRUE)) { + base <- sub("^(Lower|Upper)_95_", "", col) + l_format[[col]] <- list(l_format[[base]][[1]], col) + } + # proportions with a fixed number of decimals, so they line up + for (col in grep("^Prop_", names(df_table), value = TRUE)) { + v <- df_table[[col]] + df_table[[col]] <- ifelse(is.na(v), "-", formatC(v, format = "f", digits = dig_prop)) + } + df_table <- format_cea_table(df_table, l_format) + print(df_table) + invisible(df_table) +} + +#' Plot a comparison with a reference strategy +#' +#' Draws the incremental cost-effectiveness plane centered at the reference strategy: each +#' strategy is placed at its difference in effect (x) and cost (y) from the reference, which sits +#' at the origin. Optional segments join the reference to each strategy, forming a star, and an +#' optional willingness-to-pay line goes through the origin: strategies below the line are +#' cost-effective compared with the reference at that threshold. +#' +#' @param x a \code{cers_ref} object from \code{\link{calculate_cers_ref}} or +#' \code{\link{calculate_cers_ref_psa}}. +#' @param wtp a willingness-to-pay threshold for the dotted line through the origin. Defaults to +#' the threshold stored in \code{x}, if any; \code{NULL} draws no line. +#' @param lines whether to draw a segment from the reference to each strategy. The default +#' (\code{NULL}) draws them when there are at most 20 strategies besides the reference, since +#' with many strategies they make the plot hard to read. +#' @param label whether to label all strategies (the default) or none. +#' @param label_max_char maximum number of characters of the strategy labels; longer names are +#' truncated. The default (\code{NULL}) does not truncate. +#' @param ref_axis 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}. +#' @param currency currency symbol. Defaults to the currency stored in \code{x}, or \code{"$"}. +#' @param effect_units units of effectiveness. Defaults to \code{"QALYs"}. +#' @param col color palette for the status of each strategy: \code{"access"} (the default, an +#' accessible palette), \code{"full"}, or \code{"bw"}. +#' @param alpha opacity of the points. +#' @inheritParams add_common_aes +#' @inheritParams ggrepel::geom_label_repel +#' @param ... further arguments (not used). +#' +#' @return a \code{ggplot2} object, which can be modified by adding further layers. +#' @seealso \code{\link{calculate_cers_ref}} +#' @examples +#' df_ref <- calculate_cers_ref(cost = c(12000, 9000, 20000), +#' effect = c(8.0, 7.6, 8.5), +#' strategies = c("Standard of care", "Generic drug", "New drug"), +#' ref_str = "Standard of care") +#' plot(df_ref, wtp = 50000) +#' +#' # many strategies: no segments, no labels +#' data(hund_strat) +#' df_hund <- calculate_cers_ref(hund_strat$Cost, hund_strat$QALYs, hund_strat$Strategy, +#' ref_str = "1") +#' plot(df_hund, label = "none") +#' @importFrom ggrepel geom_label_repel +#' @export +plot.cers_ref <- function(x, + wtp = attr(x, "wtp"), + lines = NULL, + label = c("all", "none"), + label_max_char = NULL, + ref_axis = TRUE, + ref_caption = TRUE, + currency = NULL, + effect_units = "QALYs", + col = c("access", "full", "bw"), + alpha = 1, + txtsize = 12, + n_x_ticks = 6, + n_y_ticks = 6, + xbreaks = NULL, + ybreaks = NULL, + xlim = NULL, + ylim = NULL, + xexpand = expansion(0.1), + yexpand = expansion(0.1), + max.iter = 20000, + ...) { + Inc_Effect <- Inc_Cost <- Status <- Strategy <- NULL + label <- match.arg(label) + col <- match.arg(col) + currency <- resolve_currency(currency, x) + check_wtp_nhb(wtp, nhb = FALSE) + ref_str <- attr(x, "ref_str") + is_ref <- x$Strategy == ref_str + n_comp <- sum(!is_ref) + if (is.null(lines)) { + lines <- n_comp <= 20 + } + + # the reference sits at the origin of the incremental plane + df_plot <- data.frame(Strategy = x$Strategy, Status = x$Status, + Inc_Cost = ifelse(is_ref, 0, x$Inc_Cost), + Inc_Effect = ifelse(is_ref, 0, x$Inc_Effect), + stringsAsFactors = FALSE) + if (!is.null(label_max_char)) { + df_plot$Strategy <- substr(df_plot$Strategy, 1, label_max_char) + } + v_levels <- c("Dominant", "More costly, more effective", "Less costly, less effective", + "Dominated", "Equivalent") + df_comp <- df_plot[!is_ref, , drop = FALSE] + # all levels, so each status keeps its color whichever statuses are present + df_comp$Status <- factor(df_comp$Status, levels = v_levels) + df_ref <- df_plot[is_ref, , drop = FALSE] + + p <- ggplot(df_comp, aes(x = Inc_Effect, y = Inc_Cost)) + if (ref_axis) { + p <- p + + geom_hline(yintercept = 0, linetype = "dashed", color = "grey50") + + geom_vline(xintercept = 0, linetype = "dashed", color = "grey50") + } + if (lines && n_comp > 0) { + p <- p + geom_segment(aes(x = 0, y = 0, xend = Inc_Effect, yend = Inc_Cost), + color = "grey60", linewidth = 0.4) + } + if (!is.null(wtp)) { + p <- p + geom_abline(intercept = 0, slope = wtp, linetype = "dotted", color = "grey30") + } + p <- p + + geom_point(aes(color = Status), size = 2.5, alpha = alpha) + + geom_point(data = df_ref, shape = 23, size = 3.5, fill = "black", color = "black") + + labs(x = paste0("Incremental Effect (", effect_units, ")"), + y = paste0("Incremental Cost (", currency, ")")) + v_caption <- c(paste0("Reference Strategy (diamond): ", ref_str), + if (!is.null(wtp)) wtp_caption(wtp, currency, effect_units)) + if (ref_caption) { + p <- p + labs(caption = paste(v_caption, collapse = "\n")) + } + p <- add_common_aes(p, txtsize, col = col, col_aes = "color", scale_name = NULL, + continuous = c("x", "y"), + n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks, + xbreaks = xbreaks, ybreaks = ybreaks, + xlim = xlim, ylim = ylim, + xexpand = xexpand, yexpand = yexpand, + v_str = v_levels) + if (label == "all") { + p <- p + geom_label_repel(data = df_plot, aes(label = Strategy), size = 3, + show.legend = FALSE, max.iter = max.iter, direction = "both") + } + p +} diff --git a/R/evpi.R b/R/evpi.R index b67c552..d4be944 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,8 +67,11 @@ 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) -#' @param effect_units units of effectiveness. Default: QALY +#' 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, 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 @@ -77,8 +81,8 @@ calc_evpi <- function(psa, wtp, pop = 1) { #' @export plot.evpi <- function(x, txtsize = 12, - currency = "$", - effect_units = "QALY", + currency = NULL, + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -87,11 +91,12 @@ 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)) + 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 281f2ed..2719cb7 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,8 +141,11 @@ 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) -#' @param effect_units units of effectiveness. Default: QALY +#' 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, 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 @@ -149,8 +155,8 @@ calc_evppi <- function(psa, #' @export plot.evppi <- function(x, txtsize = 12, - currency = "$", - effect_units = "QALY", + currency = NULL, + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -159,13 +165,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 = "")) + 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, xbreaks = xbreaks, ybreaks = ybreaks, diff --git a/R/evsi.R b/R/evsi.R index e8af1f5..4968bae 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,8 +285,11 @@ 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) -#' @param effect_units units of effectiveness. Default: QALY +#' 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, 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 @@ -293,8 +299,8 @@ predict_matrix_tensor_smooth_ga <- function(object, #' @export plot.evsi <- function(x, txtsize = 12, - currency = "$", - effect_units = "QALY", + currency = NULL, + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -305,13 +311,15 @@ 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) 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, @@ -332,7 +340,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 ceb63e8..539946c 100644 --- a/R/exp_loss.R +++ b/R/exp_loss.R @@ -88,6 +88,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 } @@ -97,13 +98,17 @@ 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) -#' @param effect_units units of effectiveness. Default: QALY +#' 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, 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 @@ -116,10 +121,10 @@ plot.exp_loss <- function(x, log_y = TRUE, frontier = TRUE, points = TRUE, - lsize = 1, + linewidth = 1, txtsize = 12, - currency = "$", - effect_units = "QALY", + currency = NULL, + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -127,8 +132,14 @@ 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" loss_name <- "Expected_Loss" strat_name <- "Strategy" @@ -156,7 +167,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 @@ -167,7 +178,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") { @@ -175,7 +186,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 1187d2c..1b849dc 100644 --- a/R/icers.R +++ b/R/icers.R @@ -14,11 +14,27 @@ #' @param cost vector of cost for each strategy #' @param effect vector of effect for each strategy #' @param strategies string vector of strategy names +#' @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. #' -#' @seealso \code{\link{plot.icers}} +#' If \code{wtp} is given, \code{NMB} (\code{wtp * Effect - Cost}) is added. With +#' \code{nhb = TRUE}, \code{NHB} (\code{Effect - Cost / wtp}) is added too. +#' +#' The ICERs are always sequential: each strategy on the frontier is compared with the next less +#' costly one, after removing dominated and extendedly dominated strategies. This is the fully +#' incremental analysis that health technology assessment guidelines require when more than two +#' strategies are compared. To compare every strategy with a single reference strategy instead, +#' use \code{\link{calculate_cers_ref}}. +#' +#' @seealso \code{\link{plot.icers}}, \code{\link{calculate_cers_ref}} #' #' @examples #' ## Base Case @@ -52,8 +68,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") +#' +#' # the incremental cost-effectiveness plane, with the least costly strategy on the +#' # frontier at the origin +#' plot(icers, incremental = TRUE) +#' +#' ## Net monetary benefit at a willingness-to-pay threshold +#' calculate_icers(sum_cdiff$meanCost, sum_cdiff$meanEffect, sum_cdiff$Strategy, +#' wtp = 50000) #' @export -calculate_icers <- function(cost, effect, strategies) { +calculate_icers <- function(cost, effect, strategies, wtp = NULL, + nhb = FALSE, currency = NULL) { # checks on input n_cost <- length(cost) n_eff <- length(effect) @@ -64,7 +89,10 @@ calculate_icers <- function(cost, effect, strategies) { if (n_strat == 0) { stop("cost, effect, and strategies must contain at least one strategy", call. = FALSE) } + 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 @@ -85,7 +113,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_nmb(df_cea, wtp, nhb, currency)) } # three statuses: dominated, extended dominated, and non-dominated @@ -174,7 +202,63 @@ calculate_icers <- function(cost, effect, strategies) { # declare class of results class(df_results) <- c("icers", "data.frame") - df_results + add_nmb(df_results, 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 <- per_unit(effect_units) + paste0("Dotted line: WTP = ", currency, format(wtp, big.mark = ",", scientific = FALSE, trim = TRUE), + "/", unit) +} + +#' 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) +} + +#' Add net-benefit columns and stored attributes 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_nmb <- function(df_icers, wtp, nhb, currency) { + 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 (nhb) { + # net health benefit: the same comparison expressed in units of effect + df_icers$NHB <- df_icers$Effect - df_icers$Cost / wtp + } + 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. @@ -194,18 +278,23 @@ calculate_icers <- function(cost, effect, strategies) { #' 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{wtp} or \code{nhb}, the net-benefit columns described in +#' \code{\link{calculate_icers}} are added. #' @seealso \code{\link{plot.icers}} #' @seealso \code{\link{calculate_icers}} +#' @seealso \code{\link{calculate_cers_ref_psa}} to compare every strategy with a reference strategy #' @importFrom tidyr pivot_longer #' @export -calculate_icers_psa <- function(psa, uncertainty = FALSE) { +calculate_icers_psa <- function(psa, uncertainty = FALSE, wtp = NULL, nhb = FALSE) { # check that psa has class 'psa' check_psa_object(psa) @@ -213,15 +302,22 @@ calculate_icers_psa <- function(psa, uncertainty = FALSE) { # 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 # 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, + wtp = wtp, nhb = nhb, + currency = psa$currency) if (uncertainty == TRUE) { + # the joins and column selection below drop the icers class and attributes; keep them + l_attr <- attributes(df_icers)[c("class", "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 @@ -244,9 +340,16 @@ calculate_icers_psa <- function(psa, uncertainty = FALSE) { 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 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) + Inc_Cost, Inc_Effect, ICER, Status, everything()) + + df_icers <- as.data.frame(df_icers) + for (a in names(l_attr)) { + attr(df_icers, a) <- l_attr[[a]] + } } df_icers @@ -291,6 +394,19 @@ 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 incremental if \code{TRUE}, plot the incremental cost-effectiveness plane: the costs +#' and effects of every strategy are shown relative to those of the first non-dominated strategy +#' (the least costly strategy on the frontier), which is placed at the origin (0, 0). The frontier +#' and the status of each strategy do not change. Defaults to \code{FALSE} (absolute costs and +#' effects). To compare every strategy with a reference strategy of your choice, use +#' \code{\link{calculate_cers_ref}} and its \code{plot} method. +#' @param wtp a willingness-to-pay threshold. If given, a dotted line with slope \code{wtp} is +#' drawn 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{incremental = TRUE}, draw dashed axes through the origin. +#' Defaults to \code{TRUE}. +#' @param ref_caption add a caption naming the strategy at the origin (with +#' \code{incremental = TRUE}) and the WTP threshold (with \code{wtp}). Defaults to \code{TRUE}. #' @inheritParams ggrepel::geom_label_repel #' #' @return a ggplot2 object which can be modified by adding additional geoms @@ -302,7 +418,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, @@ -317,16 +433,25 @@ plot.icers <- function(x, xexpand = expansion(0.1), yexpand = expansion(0.1), max.iter = 20000, + incremental = FALSE, + wtp = NULL, + ref_axis = TRUE, + ref_caption = TRUE, ...) { - Cost <- Effect <- Status <- Strategy <- Inc_Cost <- Inc_Effect <- ICER <- NULL - - 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) + # 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") } + if (!isTRUE(incremental) && !isFALSE(incremental)) { + stop("`incremental` must be TRUE or FALSE.", call. = FALSE) + } + check_wtp_nhb(wtp, nhb = FALSE) + + # 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, net-benefit 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) @@ -355,6 +480,20 @@ plot.icers <- function(x, eff_name <- "Effect" cost_name <- "Cost" + # first non-dominated strategy: the least costly strategy on the frontier. It is the origin of + # the incremental plane and the point the WTP line goes through + df_front <- x[x$Status == nd_name, ] + df_anchor <- df_front[which.min(df_front$Cost), ] + + x_lab <- paste0("Effect (", effect_units, ")") + y_lab <- paste0("Cost (", currency, ")") + if (incremental) { + x$Cost <- x$Cost - df_anchor$Cost + x$Effect <- x$Effect - df_anchor$Effect + 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, ] @@ -369,8 +508,25 @@ 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 (incremental && 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)) { + # through the anchor strategy, which is at the origin on the incremental plane + intercept <- if (incremental) 0 else df_anchor$Cost - wtp * df_anchor$Effect + icer_plot <- icer_plot + + geom_abline(intercept = intercept, slope = wtp, linetype = "dotted", color = "grey30") + } + v_caption <- c(if (incremental) paste0("Origin: ", df_anchor$Strategy, + " (least costly strategy on the frontier)"), + 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"), @@ -406,8 +562,12 @@ plot.icers <- function(x, #' Print the formatted CEA table #' +#' Prints the sequential cost-effectiveness table: each strategy on the frontier is compared with +#' the previous one. +#' #' @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 @@ -415,7 +575,7 @@ plot.icers <- function(x, #' @return a dataframe object - formatted CEA table #' @export print.icers <- function(x, - currency = "$", + currency = NULL, dig_cost = 0, dig_eff = 2, dig_icer = 0, @@ -424,7 +584,37 @@ print.icers <- function(x, if (!inherits(x, "icers")) { stop("x must be an object of class icers") } + if (is.null(currency)) { + currency <- if (is.null(attr(x, "currency"))) "$" else attr(x, "currency") + } + + df_table_cea <- x + class(df_table_cea) <- "data.frame" + + # display digits and header for each known column + 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)")), + NMB = list(dig_cost, paste0("NMB (", currency, ")")), + NHB = list(dig_eff, "NHB (QALYs)") + ) + df_table_cea <- format_cea_table(df_table_cea, l_format) + print(df_table_cea) + invisible(df_table_cea) +} + +#' Format the numeric columns of a CEA table for printing +#' +#' @param df_table data frame to format. +#' @param l_format named list, one element per column to format: a list of the number of digits +#' (\code{NA} to leave the column as it is) and the header to print. +#' @return \code{df_table} with the formatted columns, as character, and renamed. +#' @keywords internal +format_cea_table <- function(df_table, l_format) { format_numbers <- function(col, n_digits) { v_new_col <- rep("-", length(col)) v_non_na <- !is.na(col) @@ -435,30 +625,13 @@ print.icers <- function(x, v_new_col[v_non_na] <- format(round(col[v_non_na], n_digits), big.mark = ",", nsmall = n_digits, scientific = FALSE) } - 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)")) - - class(df_table_cea) <- "data.frame" - print(df_table_cea) - invisible(df_table_cea) + for (col in intersect(names(l_format), names(df_table))) { + if (!is.na(l_format[[col]][[1]])) { + df_table[[col]] <- format_numbers(df_table[[col]], n_digits = l_format[[col]][[1]]) + } + names(df_table)[names(df_table) == col] <- l_format[[col]][[2]] + } + df_table } diff --git a/R/metamodel.R b/R/metamodel.R index 572452f..7ea9f6f 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/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/psa.R b/R/psa.R index 56b114e..2013e66 100644 --- a/R/psa.R +++ b/R/psa.R @@ -139,7 +139,18 @@ 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 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. +#' @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 @@ -162,6 +173,9 @@ plot.psa <- function(x, ylim = NULL, ref_axis = TRUE, ref_caption = TRUE, + wtp = NULL, + xtrans = "identity", + ytrans = "identity", ...) { Effectiveness <- Cost <- Strategy <- Eff.mean <- Cost.mean <- y <- group <- NULL @@ -169,6 +183,8 @@ 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) + check_wtp_nhb(wtp, nhb = FALSE) if (is.null(ref_str)) { # expect that effectiveness and costs have strategy column names @@ -192,6 +208,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 = "")) @@ -212,21 +229,25 @@ 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), 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) # only the center points use fill; a fill scale without them makes ggplot2 warn @@ -236,17 +257,15 @@ 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 { - ### 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 } @@ -273,6 +292,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 = "")) + @@ -284,9 +304,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 @@ -305,15 +332,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), @@ -329,7 +348,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/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/README.Rmd b/README.Rmd index b792e58..9237d51 100644 --- a/README.Rmd +++ b/README.Rmd @@ -35,7 +35,7 @@ dampack does these analyses in R for any model. It only needs the model's output ## What it does -- **Cost-effectiveness analysis.** `calculate_icers()` identifies dominated and extendedly dominated strategies and computes ICERs along the efficient frontier; `plot()` draws the frontier. +- **Cost-effectiveness analysis.** `calculate_icers()` identifies dominated and extendedly dominated strategies and computes ICERs along the efficient frontier; `plot()` draws the frontier on absolute or incremental axes. Where guidelines allow it alongside this fully incremental analysis, `calculate_cers_ref()` also compares every strategy with a single reference strategy, such as the standard of care. - **Probabilistic sensitivity analysis.** `make_psa_obj()` stores the PSA output of any model. Its `plot()` and `summary()` methods show the cost-effectiveness plane, `ceac()` computes cost-effectiveness acceptability curves (CEACs) together with the acceptability frontier (CEAF), and `calc_exp_loss()` computes expected loss curves (ELCs), which show in one figure the expected foregone benefit of each strategy, the optimal strategy, and the expected value of perfect information ([Alarid-Escudero et al., 2019](https://doi.org/10.1016/j.jval.2019.02.008)). - **Value of information.** `calc_evpi()` computes the expected value of perfect information (EVPI). `calc_evppi()` estimates the expected value of partial perfect information (EVPPI) with regression metamodels of the PSA ([Strong et al., 2014](https://doi.org/10.1177/0272989X13505910); [Jalal and Alarid-Escudero, 2018](https://doi.org/10.1177/0272989X17715627)), and `calc_evsi()` estimates the expected value of sample information (EVSI) of a future study with the Gaussian approximation approach ([Jalal and Alarid-Escudero, 2018](https://doi.org/10.1177/0272989X17715627)). Both work from the PSA sample you already have, so no further model runs are needed. - **Deterministic sensitivity analysis.** One-way and two-way analyses come either from the PSA, through metamodels (`owsa()`, `twsa()`), or from running your model directly (`run_owsa_det()`, `run_twsa_det()`), with tornado diagrams and optimal-strategy plots. diff --git a/README.md b/README.md index 6431c58..2569fa8 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,11 @@ scientists, health economists, and students. - **Cost-effectiveness analysis.** `calculate_icers()` identifies dominated and extendedly dominated strategies and computes ICERs along - the efficient frontier; `plot()` draws the frontier. + the efficient frontier; `plot()` draws the frontier on absolute or + incremental axes. Where guidelines allow it alongside this fully + incremental analysis, `calculate_cers_ref()` also compares every + strategy with a single reference strategy, such as the standard of + care. - **Probabilistic sensitivity analysis.** `make_psa_obj()` stores the PSA output of any model. Its `plot()` and `summary()` methods show the cost-effectiveness plane, `ceac()` computes cost-effectiveness diff --git a/_pkgdown.yml b/_pkgdown.yml index 2219e97..f4e24c1 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -50,6 +50,17 @@ reference: - print.icers - plot.icers + - title: Comparisons with a reference strategy + desc: > + Compare every strategy with a single reference strategy, such as + the standard of care, where guidelines allow it alongside the fully + incremental analysis. + contents: + - calculate_cers_ref + - calculate_cers_ref_psa + - print.cers_ref + - plot.cers_ref + - title: Probabilistic sensitivity analysis (PSA) objects desc: > Build a `psa` object from the costs, effects, and parameter draws of any diff --git a/man/add_cers_ref_uncertainty.Rd b/man/add_cers_ref_uncertainty.Rd new file mode 100644 index 0000000..053f30b --- /dev/null +++ b/man/add_cers_ref_uncertainty.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cers_ref.R +\name{add_cers_ref_uncertainty} +\alias{add_cers_ref_uncertainty} +\title{Add PSA intervals and quadrant proportions to a \code{cers_ref} object} +\usage{ +add_cers_ref_uncertainty(df_ref, psa, wtp, nhb) +} +\arguments{ +\item{df_ref}{a \code{cers_ref} object computed from the means of \code{psa}.} + +\item{psa}{the \code{psa} object.} + +\item{wtp}{a single willingness-to-pay threshold (currency per unit of effect). If given, the +net monetary benefit of each strategy and its difference from the reference are added. +The default (\code{NULL}) adds no net-benefit columns.} + +\item{nhb}{if \code{TRUE}, also add the net health benefit and its difference from the +reference. Requires \code{wtp}.} +} +\value{ +\code{df_ref} with the columns described in \code{\link{calculate_cers_ref_psa}}. +} +\description{ +Add PSA intervals and quadrant proportions to a \code{cers_ref} object +} +\keyword{internal} diff --git a/man/add_nmb.Rd b/man/add_nmb.Rd new file mode 100644 index 0000000..c7764b4 --- /dev/null +++ b/man/add_nmb.Rd @@ -0,0 +1,28 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/icers.R +\name{add_nmb} +\alias{add_nmb} +\title{Add net-benefit columns and stored attributes to an icers object} +\usage{ +add_nmb(df_icers, wtp, nhb, currency) +} +\arguments{ +\item{df_icers}{an \code{icers} object.} + +\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_cers_ref.Rd b/man/calculate_cers_ref.Rd new file mode 100644 index 0000000..144c920 --- /dev/null +++ b/man/calculate_cers_ref.Rd @@ -0,0 +1,114 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cers_ref.R +\name{calculate_cers_ref} +\alias{calculate_cers_ref} +\title{Compare every strategy with a reference strategy} +\usage{ +calculate_cers_ref( + cost, + effect, + strategies, + ref_str, + wtp = NULL, + nhb = FALSE, + currency = NULL +) +} +\arguments{ +\item{cost}{vector of cost for each strategy.} + +\item{effect}{vector of effect for each strategy.} + +\item{strategies}{string vector of strategy names.} + +\item{ref_str}{name of the reference strategy, one of \code{strategies}, for example +\code{"Standard of care"}.} + +\item{wtp}{a single willingness-to-pay threshold (currency per unit of effect). If given, the +net monetary benefit of each strategy and its difference from the reference are added. +The default (\code{NULL}) adds no net-benefit columns.} + +\item{nhb}{if \code{TRUE}, also add the net health benefit and its difference from the +reference. 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 of class \code{cers_ref}, with the reference strategy in the first row +and the other strategies by increasing cost, and these columns: +\describe{ + \item{Strategy, Cost, Effect}{as given.} + \item{Inc_Cost, Inc_Effect}{cost and effect minus those of the reference.} + \item{CER}{\code{Inc_Cost / Inc_Effect}, the cost-effectiveness ratio compared with the + reference. It is \code{NA} where a ratio is not meaningful: for the reference itself and for + dominant, dominated and equivalent strategies.} + \item{Status}{one of \code{"Reference"}, \code{"Dominant"} (not more costly and at least as + effective), \code{"Dominated"} (not less costly and no more effective), + \code{"More costly, more effective"}, \code{"Less costly, less effective"}, or + \code{"Equivalent"} (same cost and effect).} + \item{NMB, Inc_NMB}{with \code{wtp}: the net monetary benefit, \code{wtp * Effect - Cost}, + and its difference from the reference. A strategy with a positive \code{Inc_NMB} is + cost-effective compared with the reference at this threshold.} + \item{NHB, Inc_NHB}{with \code{nhb = TRUE}: the net health benefit, + \code{Effect - Cost / wtp}, and its difference from the reference.} +} +The reference strategy, threshold and currency are stored as attributes, which the +\code{print} and \code{plot} methods use. + +For a strategy that is more costly and more effective than the reference, a \code{CER} below +the willingness-to-pay threshold means it is cost-effective compared with the reference. For a +strategy that is less costly and less effective, the \code{CER} is the cost saved per unit of +effect lost, and the strategy is cost-effective compared with the reference when its +\code{CER} is \emph{above} the threshold. +} +\description{ +Compares each strategy with a single reference strategy chosen by the user, such as the +current standard of care: the difference in cost and in effect from the reference, the +cost-effectiveness ratio (CER) of that difference, and where each strategy lies on the +incremental cost-effectiveness plane centered at the reference. + +These comparisons are \emph{not} the incremental cost-effectiveness ratios (ICERs) of a +fully incremental analysis. When more than two strategies are compared, health technology +assessment guidelines require a fully incremental (sequential) analysis, in which dominated +and extendedly dominated strategies are removed and each strategy on the cost-effectiveness +frontier is compared with the next less costly one: use \code{\link{calculate_icers}} for that. +Comparisons with a single reference are a complement for settings where they are relevant +and justified. The NICE manual (2022), for example, states that "pairwise comparisons may be +presented when relevant and justified (for example, when the technology is expected to +specifically displace individual comparators)", after requiring a fully incremental +analysis. The CDA-AMC (2017) and Zorginstituut Nederland (2024) guidelines also require a +sequential analysis when more than two interventions are compared. +} +\examples{ +# three strategies; "Standard of care" is neither the cheapest nor the least effective +df_ref <- calculate_cers_ref(cost = c(12000, 9000, 20000), + effect = c(8.0, 7.6, 8.5), + strategies = c("Standard of care", "Generic drug", "New drug"), + ref_str = "Standard of care", + wtp = 50000) +df_ref +plot(df_ref) + +# the fully incremental analysis of the same strategies +calculate_icers(cost = c(12000, 9000, 20000), + effect = c(8.0, 7.6, 8.5), + strategies = c("Standard of care", "Generic drug", "New drug")) +} +\references{ +National Institute for Health and Care Excellence (NICE). NICE health technology evaluations: +the manual (PMG36), section 4.6, "Economic evaluation". London: NICE; 2022. +\url{https://www.nice.org.uk/process/pmg36/chapter/economic-evaluation-2} + +CDA-AMC (formerly CADTH). Guidelines for the Economic Evaluation of Health Technologies: +Canada. 4th ed. Ottawa: CADTH; 2017. +\url{https://www.cda-amc.ca/sites/default/files/pdf/guidelines_for_the_economic_evaluation_of_health_technologies_canada_4th_ed.pdf} + +Zorginstituut Nederland. Guideline for economic evaluations in healthcare (2024 version). +Diemen: Zorginstituut Nederland; 2024. +\url{https://english.zorginstituutnederland.nl/documents/2024/01/16/guideline-for-economic-evaluations-in-healthcare} +} +\seealso{ +\code{\link{plot.cers_ref}}, \code{\link{calculate_cers_ref_psa}} for the same +comparison from a PSA, and \code{\link{calculate_icers}} for the fully incremental analysis. +} diff --git a/man/calculate_cers_ref_psa.Rd b/man/calculate_cers_ref_psa.Rd new file mode 100644 index 0000000..0a30074 --- /dev/null +++ b/man/calculate_cers_ref_psa.Rd @@ -0,0 +1,85 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cers_ref.R +\name{calculate_cers_ref_psa} +\alias{calculate_cers_ref_psa} +\title{Compare every strategy with a reference strategy, from a \code{psa} object} +\usage{ +calculate_cers_ref_psa( + psa, + ref_str, + wtp = NULL, + nhb = FALSE, + uncertainty = FALSE +) +} +\arguments{ +\item{psa}{\code{psa} object from \code{\link{make_psa_obj}}.} + +\item{ref_str}{name of the reference strategy, one of \code{strategies}, for example +\code{"Standard of care"}.} + +\item{wtp}{a single willingness-to-pay threshold (currency per unit of effect). If given, the +net monetary benefit of each strategy and its difference from the reference are added. +The default (\code{NULL}) adds no net-benefit columns.} + +\item{nhb}{if \code{TRUE}, also add the net health benefit and its difference from the +reference. Requires \code{wtp}.} + +\item{uncertainty}{if \code{TRUE}, add the 95\% intervals and quadrant proportions described +in Value. Defaults to \code{FALSE}.} +} +\value{ +A \code{cers_ref} object with the columns described in +\code{\link{calculate_cers_ref}}, computed from the mean cost and effect of each strategy. The +currency of \code{psa} is kept. + +With \code{uncertainty = TRUE}, the differences from the reference are computed in every PSA +sample, and these columns are added (\code{NA} for the reference itself): +\itemize{ + \item \code{Lower_95_Inc_Cost} and \code{Upper_95_Inc_Cost}, the 2.5th and 97.5th + percentiles of the difference in cost, placed after \code{Inc_Cost}; likewise for + \code{Inc_Effect} and, with \code{wtp}, \code{Inc_NMB} (and \code{Inc_NHB}). + \item \code{Prop_NE}, \code{Prop_SE}, \code{Prop_SW}, and \code{Prop_NW}, 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; SW not more effective and not more + costly; NW not more effective and more costly. The four proportions sum to 1. + \item With \code{wtp}, \code{Prop_CE}, the proportion of samples in which the strategy is + cost-effective compared with the reference (it has a higher net monetary benefit). +} +} +\description{ +Compares each strategy with a reference strategy using the mean costs and effects of a +probabilistic sensitivity analysis (PSA), as \code{\link{calculate_cers_ref}} does for a base +case. With \code{uncertainty = TRUE}, it also summarizes the uncertainty in each comparison +across the PSA samples. See \code{\link{calculate_cers_ref}} for when a comparison with a +single reference is appropriate, and \code{\link{calculate_icers_psa}} for the fully +incremental analysis. +} +\examples{ +data(cancer_psa_data) +l_psa <- make_psa_obj(cost = cancer_psa_data$cost, + effectiveness = cancer_psa_data$effectiveness, + parameters = cancer_psa_data$parameters, + strategies = cancer_psa_data$strategies) +df_ref <- calculate_cers_ref_psa(l_psa, ref_str = "Radio", wtp = 50000, + uncertainty = TRUE) +df_ref +plot(df_ref) +} +\references{ +National Institute for Health and Care Excellence (NICE). NICE health technology evaluations: +the manual (PMG36), section 4.6, "Economic evaluation". London: NICE; 2022. +\url{https://www.nice.org.uk/process/pmg36/chapter/economic-evaluation-2} + +CDA-AMC (formerly CADTH). Guidelines for the Economic Evaluation of Health Technologies: +Canada. 4th ed. Ottawa: CADTH; 2017. +\url{https://www.cda-amc.ca/sites/default/files/pdf/guidelines_for_the_economic_evaluation_of_health_technologies_canada_4th_ed.pdf} + +Zorginstituut Nederland. Guideline for economic evaluations in healthcare (2024 version). +Diemen: Zorginstituut Nederland; 2024. +\url{https://english.zorginstituutnederland.nl/documents/2024/01/16/guideline-for-economic-evaluations-in-healthcare} +} +\seealso{ +\code{\link{calculate_cers_ref}}, \code{\link{plot.cers_ref}}, and +\code{\link{plot.psa}} with \code{ref_str} for the PSA samples on the incremental plane. +} diff --git a/man/calculate_icers.Rd b/man/calculate_icers.Rd index 9b988b1..c42d49e 100644 --- a/man/calculate_icers.Rd +++ b/man/calculate_icers.Rd @@ -4,7 +4,14 @@ \alias{calculate_icers} \title{Calculate incremental cost-effectiveness ratios (ICERs)} \usage{ -calculate_icers(cost, effect, strategies) +calculate_icers( + cost, + effect, + strategies, + wtp = NULL, + nhb = FALSE, + currency = NULL +) } \arguments{ \item{cost}{vector of cost for each strategy} @@ -12,10 +19,29 @@ calculate_icers(cost, effect, strategies) \item{effect}{vector of effect for each strategy} \item{strategies}{string vector of strategy names} + +\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{wtp} is given, \code{NMB} (\code{wtp * Effect - Cost}) is added. With +\code{nhb = TRUE}, \code{NHB} (\code{Effect - Cost / wtp}) is added too. + +The ICERs are always sequential: each strategy on the frontier is compared with the next less +costly one, after removing dominated and extendedly dominated strategies. This is the fully +incremental analysis that health technology assessment guidelines require when more than two +strategies are compared. To compare every strategy with a single reference strategy instead, +use \code{\link{calculate_cers_ref}}. } \description{ This function takes in strategies and their associated cost and effect, assigns them @@ -60,7 +86,15 @@ 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") + +# the incremental cost-effectiveness plane, with the least costly strategy on the +# frontier at the origin +plot(icers, incremental = TRUE) + +## Net monetary benefit at a willingness-to-pay threshold +calculate_icers(sum_cdiff$meanCost, sum_cdiff$meanEffect, sum_cdiff$Strategy, + wtp = 50000) } \seealso{ -\code{\link{plot.icers}} +\code{\link{plot.icers}}, \code{\link{calculate_cers_ref}} } diff --git a/man/calculate_icers_psa.Rd b/man/calculate_icers_psa.Rd index 14b56d8..a672a51 100644 --- a/man/calculate_icers_psa.Rd +++ b/man/calculate_icers_psa.Rd @@ -4,19 +4,28 @@ \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, 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{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{wtp} or \code{nhb}, the net-benefit columns described in +\code{\link{calculate_icers}} are added. } \description{ The mean costs and QALYs for each strategy in a PSA are used @@ -37,4 +46,6 @@ even if present in the ICER table. \code{\link{plot.icers}} \code{\link{calculate_icers}} + +\code{\link{calculate_cers_ref_psa}} to compare every strategy with a reference strategy } 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/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/check_ref_str.Rd b/man/check_ref_str.Rd new file mode 100644 index 0000000..d888f0c --- /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/cers_ref.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/format_cea_table.Rd b/man/format_cea_table.Rd new file mode 100644 index 0000000..d5bec25 --- /dev/null +++ b/man/format_cea_table.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/icers.R +\name{format_cea_table} +\alias{format_cea_table} +\title{Format the numeric columns of a CEA table for printing} +\usage{ +format_cea_table(df_table, l_format) +} +\arguments{ +\item{df_table}{data frame to format.} + +\item{l_format}{named list, one element per column to format: a list of the number of digits +(\code{NA} to leave the column as it is) and the header to print.} +} +\value{ +\code{df_table} with the formatted columns, as character, and renamed. +} +\description{ +Format the numeric columns of a CEA table for printing +} +\keyword{internal} 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/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 ee09f84..1b648e8 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 = "QALYs", ... ) } @@ -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,10 @@ 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, 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.cers_ref.Rd b/man/plot.cers_ref.Rd new file mode 100644 index 0000000..22a3d92 --- /dev/null +++ b/man/plot.cers_ref.Rd @@ -0,0 +1,114 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cers_ref.R +\name{plot.cers_ref} +\alias{plot.cers_ref} +\title{Plot a comparison with a reference strategy} +\usage{ +\method{plot}{cers_ref}( + x, + wtp = attr(x, "wtp"), + lines = NULL, + label = c("all", "none"), + label_max_char = NULL, + ref_axis = TRUE, + ref_caption = TRUE, + currency = NULL, + effect_units = "QALYs", + col = c("access", "full", "bw"), + alpha = 1, + txtsize = 12, + n_x_ticks = 6, + n_y_ticks = 6, + xbreaks = NULL, + ybreaks = NULL, + xlim = NULL, + ylim = NULL, + xexpand = expansion(0.1), + yexpand = expansion(0.1), + max.iter = 20000, + ... +) +} +\arguments{ +\item{x}{a \code{cers_ref} object from \code{\link{calculate_cers_ref}} or +\code{\link{calculate_cers_ref_psa}}.} + +\item{wtp}{a willingness-to-pay threshold for the dotted line through the origin. Defaults to +the threshold stored in \code{x}, if any; \code{NULL} draws no line.} + +\item{lines}{whether to draw a segment from the reference to each strategy. The default +(\code{NULL}) draws them when there are at most 20 strategies besides the reference, since +with many strategies they make the plot hard to read.} + +\item{label}{whether to label all strategies (the default) or none.} + +\item{label_max_char}{maximum number of characters of the strategy labels; longer names are +truncated. The default (\code{NULL}) does not truncate.} + +\item{ref_axis}{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{currency}{currency symbol. Defaults to the currency stored in \code{x}, or \code{"$"}.} + +\item{effect_units}{units of effectiveness. Defaults to \code{"QALYs"}.} + +\item{col}{color palette for the status of each strategy: \code{"access"} (the default, an +accessible palette), \code{"full"}, or \code{"bw"}.} + +\item{alpha}{opacity of the points.} + +\item{txtsize}{base text size} + +\item{n_x_ticks}{number of x-axis ticks} + +\item{n_y_ticks}{number of y-axis ticks} + +\item{xbreaks}{vector of x-axis breaks. +will override \code{n_x_ticks} if provided.} + +\item{ybreaks}{vector of y-axis breaks. +will override \code{n_y_ticks} if provided.} + +\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{xexpand}{Padding around data. See \code{\link[ggplot2]{scale_continuous}} for details.} + +\item{yexpand}{Padding around data. See \code{\link[ggplot2]{scale_continuous}} for details. +The default behavior in ggplot2 is \code{expansion(0.05)}. See \code{\link[ggplot2]{expansion}} +for how to modify this.} + +\item{max.iter}{Maximum number of iterations to try to resolve overlaps. +Defaults to 10000.} + +\item{...}{further arguments (not used).} +} +\value{ +a \code{ggplot2} object, which can be modified by adding further layers. +} +\description{ +Draws the incremental cost-effectiveness plane centered at the reference strategy: each +strategy is placed at its difference in effect (x) and cost (y) from the reference, which sits +at the origin. Optional segments join the reference to each strategy, forming a star, and an +optional willingness-to-pay line goes through the origin: strategies below the line are +cost-effective compared with the reference at that threshold. +} +\examples{ +df_ref <- calculate_cers_ref(cost = c(12000, 9000, 20000), + effect = c(8.0, 7.6, 8.5), + strategies = c("Standard of care", "Generic drug", "New drug"), + ref_str = "Standard of care") +plot(df_ref, wtp = 50000) + +# many strategies: no segments, no labels +data(hund_strat) +df_hund <- calculate_cers_ref(hund_strat$Cost, hund_strat$QALYs, hund_strat$Strategy, + ref_str = "1") +plot(df_hund, label = "none") +} +\seealso{ +\code{\link{calculate_cers_ref}} +} diff --git a/man/plot.evpi.Rd b/man/plot.evpi.Rd index bb878a6..49fc72d 100644 --- a/man/plot.evpi.Rd +++ b/man/plot.evpi.Rd @@ -7,8 +7,8 @@ \method{plot}{evpi}( x, txtsize = 12, - currency = "$", - effect_units = "QALY", + currency = NULL, + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -25,9 +25,12 @@ \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} +\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 0174fd5..5584a62 100644 --- a/man/plot.evppi.Rd +++ b/man/plot.evppi.Rd @@ -7,8 +7,8 @@ \method{plot}{evppi}( x, txtsize = 12, - currency = "$", - effect_units = "QALY", + currency = NULL, + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -25,9 +25,12 @@ \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} +\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 fdc8186..0954135 100644 --- a/man/plot.evsi.Rd +++ b/man/plot.evsi.Rd @@ -7,8 +7,8 @@ \method{plot}{evsi}( x, txtsize = 12, - currency = "$", - effect_units = "QALY", + currency = NULL, + effect_units = "QALYs", n_y_ticks = 8, n_x_ticks = 20, xbreaks = NULL, @@ -26,9 +26,12 @@ \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} +\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 5e4322e..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 = "$", - effect_units = "QALY", + currency = NULL, + 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,14 +35,17 @@ 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} \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} +\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} @@ -59,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.icers.Rd b/man/plot.icers.Rd index 132c482..bd06faf 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, + incremental = FALSE, + wtp = NULL, + ref_axis = TRUE, + ref_caption = TRUE, ... ) } @@ -67,6 +71,23 @@ for how to modify this.} \item{max.iter}{Maximum number of iterations to try to resolve overlaps. Defaults to 10000.} +\item{incremental}{if \code{TRUE}, plot the incremental cost-effectiveness plane: the costs +and effects of every strategy are shown relative to those of the first non-dominated strategy +(the least costly strategy on the frontier), which is placed at the origin (0, 0). The frontier +and the status of each strategy do not change. Defaults to \code{FALSE} (absolute costs and +effects). To compare every strategy with a reference strategy of your choice, use +\code{\link{calculate_cers_ref}} and its \code{plot} method.} + +\item{wtp}{a willingness-to-pay threshold. If given, a dotted line with slope \code{wtp} is +drawn 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{incremental = TRUE}, draw dashed axes through the origin. +Defaults to \code{TRUE}.} + +\item{ref_caption}{add a caption naming the strategy at the origin (with +\code{incremental = TRUE}) and the WTP threshold (with \code{wtp}). 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.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.psa.Rd b/man/plot.psa.Rd index 32bbf8c..67391ea 100644 --- a/man/plot.psa.Rd +++ b/man/plot.psa.Rd @@ -20,6 +20,9 @@ ylim = NULL, ref_axis = TRUE, ref_caption = TRUE, + wtp = NULL, + xtrans = "identity", + ytrans = "identity", ... ) } @@ -56,7 +59,20 @@ 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 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{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/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/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/print.cers_ref.Rd b/man/print.cers_ref.Rd new file mode 100644 index 0000000..4ebffff --- /dev/null +++ b/man/print.cers_ref.Rd @@ -0,0 +1,38 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cers_ref.R +\name{print.cers_ref} +\alias{print.cers_ref} +\title{Print a comparison with a reference strategy} +\usage{ +\method{print}{cers_ref}( + x, + currency = NULL, + dig_cost = 0, + dig_eff = 2, + dig_cer = 0, + dig_prop = 3, + ... +) +} +\arguments{ +\item{x}{a \code{cers_ref} object.} + +\item{currency}{currency symbol. Defaults to the currency stored in \code{x}, or \code{"$"}.} + +\item{dig_cost}{number of digits to round costs and net monetary benefits to.} + +\item{dig_eff}{number of digits to round effects and net health benefits to.} + +\item{dig_cer}{number of digits to round the cost-effectiveness ratios to.} + +\item{dig_prop}{number of digits to round the proportions of PSA samples to.} + +\item{...}{further arguments (not used).} +} +\value{ +the formatted table, invisibly. +} +\description{ +Prints the table of a \code{\link{calculate_cers_ref}} object with formatted numbers and +headers that name the reference strategy. +} diff --git a/man/print.icers.Rd b/man/print.icers.Rd index a010fc5..677b0f4 100644 --- a/man/print.icers.Rd +++ b/man/print.icers.Rd @@ -4,12 +4,13 @@ \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, ...) } \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} @@ -23,5 +24,6 @@ a dataframe object - formatted CEA table } \description{ -Print the formatted CEA table +Prints the sequential cost-effectiveness table: each strategy on the frontier is compared with +the previous one. } 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/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/status_vs_reference.Rd b/man/status_vs_reference.Rd new file mode 100644 index 0000000..8fcd925 --- /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/cers_ref.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/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/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/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_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_calculate_icers.R b/tests/testthat/test_calculate_icers.R index 418b8bc..4a8ec33 100644 --- a/tests/testthat/test_calculate_icers.R +++ b/tests/testthat/test_calculate_icers.R @@ -90,7 +90,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_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_cers_ref.R b/tests/testthat/test_cers_ref.R new file mode 100644 index 0000000..4afebc2 --- /dev/null +++ b/tests/testthat/test_cers_ref.R @@ -0,0 +1,178 @@ +# calculate_cers_ref() and calculate_cers_ref_psa(): every strategy against a reference (#209) + +# 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 (CER 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 (CER 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_cers <- function(ref_str = "Ref", ...) { + calculate_cers_ref(df_toy$cost, df_toy$effect, df_toy$strategy, ref_str = ref_str, ...) +} +row_of <- function(x, s) x[x$Strategy == s, ] + +test_that("comparisons with the reference match hand calculations", { + x <- toy_cers() + expect_s3_class(x, "cers_ref") + expect_identical(names(x), c("Strategy", "Cost", "Effect", "Inc_Cost", "Inc_Effect", "CER", "Status")) + 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, expected[[s]][[1]], info = s) + expect_equal(r$Inc_Effect, expected[[s]][[2]], info = s) + expect_equal(r$CER, expected[[s]][[3]], info = s) + expect_equal(r$Status, expected[[s]][[4]], info = s) + } + expect_type(x$CER, "double") +}) + +test_that("the reference comes first, then the other strategies by cost", { + x <- toy_cers(ref_str = "More") + expect_equal(x$Strategy, c("More", "Cheaper", "Less", "Ref", "Same", "Worse")) + + data(hund_strat) + y <- calculate_cers_ref(hund_strat$Cost, hund_strat$QALYs, hund_strat$Strategy, ref_str = "1") + v_rest <- hund_strat[hund_strat$Strategy != 1, ] + expect_equal(y$Strategy, c("1", as.character(v_rest$Strategy[order(v_rest$Cost)]))) + r0 <- row_of(y, "1") + others <- y$Strategy != "1" + expect_equal(y$Inc_Cost[others], y$Cost[others] - r0$Cost) + expect_equal(y$Inc_Effect[others], y$Effect[others] - r0$Effect) +}) + +test_that("a dominated or the most expensive strategy can be the reference", { + x <- toy_cers(ref_str = "Worse") # Worse is dominated and the most expensive strategy + expect_equal(row_of(x, "Worse")$Status, "Reference") + expect_equal(row_of(x, "Cheaper")$Status, "Dominant") + expect_equal(row_of(x, "Cheaper")$Inc_Cost, 50 - 300) + expect_true(all(x$Inc_Cost[x$Strategy != "Worse"] < 0)) +}) + +test_that("wtp adds NMB and its difference from the reference; nhb adds NHB", { + x <- toy_cers(wtp = 150) + expect_equal(x$NMB, 150 * x$Effect - x$Cost) + expect_equal(row_of(x, "More")$Inc_NMB, (150 * 2 - 200) - (150 * 1 - 100)) + expect_true(is.na(row_of(x, "Ref")$Inc_NMB)) + expect_false(any(c("NHB", "Inc_NHB") %in% names(x))) + expect_identical(attr(x, "wtp"), 150) + + z <- toy_cers(wtp = 150, nhb = TRUE) + expect_equal(z$NHB, z$Effect - z$Cost / 150) + expect_equal(row_of(z, "Cheaper")$Inc_NHB, (1.5 - 50 / 150) - (1 - 100 / 150)) +}) + +test_that("edge cases: one strategy, two strategies, names with spaces", { + one <- calculate_cers_ref(10, 1, "Standard of care", ref_str = "Standard of care", wtp = 100) + expect_equal(one$Status, "Reference") + expect_equal(one$NMB, 90) + + two <- calculate_cers_ref(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)")$CER, 20) + expect_equal(row_of(two, "New drug (A)")$Status, "More costly, more effective") +}) + +test_that("invalid inputs give informative errors", { + expect_error(calculate_cers_ref(df_toy$cost, df_toy$effect, df_toy$strategy), "must name the reference") + expect_error(toy_cers(ref_str = "Nope"), "must be one of the strategies") + expect_error(toy_cers(ref_str = c("Ref", "More")), "single strategy name") + expect_error(toy_cers(wtp = c(100, 200)), "single non-negative number") + expect_error(toy_cers(wtp = -1), "single non-negative number") + expect_error(toy_cers(nhb = TRUE), "requires `wtp`") + expect_error(calculate_cers_ref(1:2, 1:3, c("a", "b"), ref_str = "a"), "same length") + expect_error(calculate_cers_ref(1:2, 1:2, c("a", "a"), ref_str = "a"), "unique") +}) + +test_that("print() names the reference and formats the table", { + x <- toy_cers(wtp = 150, currency = "€") + out <- capture.output(tbl <- print(x)) + expect_true(any(grepl("not a fully incremental analysis", out, fixed = TRUE))) + expect_true("CER vs Ref (€/QALY)" %in% names(tbl)) + expect_true("Incremental NMB vs Ref (€)" %in% names(tbl)) + expect_equal(tbl[["CER vs Ref (€/QALY)"]][1], "-") +}) + +# calculate_icers() stays fully incremental: no reference strategy +test_that("calculate_icers() has no reference strategy", { + expect_false("ref_str" %in% names(formals(calculate_icers))) + expect_false("ref_str" %in% names(formals(calculate_icers_psa))) + expect_false("ref_str" %in% names(formals(summary.psa))) + x <- calculate_icers(df_toy$cost, df_toy$effect, df_toy$strategy) + expect_identical(names(x), c("Strategy", "Cost", "Effect", "Inc_Cost", "Inc_Effect", "ICER", "Status")) + y <- calculate_icers(df_toy$cost, df_toy$effect, df_toy$strategy, wtp = 150, nhb = TRUE) + expect_equal(y$NMB, 150 * y$Effect - y$Cost) + expect_equal(y$NHB, y$Effect - y$Cost / 150) + expect_identical(attr(y, "wtp"), 150) + expect_error(calculate_icers(df_toy$cost, df_toy$effect, df_toy$strategy, nhb = TRUE), + "requires `wtp`") +}) + +# PSA ---------------------------------------------------------------------------------------- + +# 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"), currency = "€") + +test_that("calculate_cers_ref_psa() uses the means of the PSA and keeps its currency", { + s <- summary(psa_q) + expected <- calculate_cers_ref(s$meanCost, s$meanEffect, s$Strategy, ref_str = "Ref", + wtp = 1000, currency = "€") + expect_equal(calculate_cers_ref_psa(psa_q, ref_str = "Ref", wtp = 1000), expected) + expect_identical(attr(expected, "currency"), "€") +}) + +test_that("uncertainty = TRUE gives quadrant shares and the share of cost-effective samples", { + x <- calculate_cers_ref_psa(psa_q, ref_str = "Ref", wtp = 1000, uncertainty = TRUE) + r_new <- row_of(x, "New") + expect_equal(unlist(r_new[, c("Prop_NE", "Prop_SE", "Prop_SW", "Prop_NW")], use.names = FALSE), + rep(0.25, 4)) + inmb <- 1000 * (df_eff$New - df_eff$Ref) - (df_cost$New - df_cost$Ref) # 100, 250, -50, -200 + expect_equal(r_new$Prop_CE, mean(inmb > 0)) + expect_equal(r_new$Lower_95_Inc_NMB, unname(quantile(inmb, 0.025))) + r_ref <- row_of(x, "Ref") + expect_true(all(is.na(r_ref[, c("Lower_95_Inc_Cost", "Prop_NE", "Prop_CE")]))) + # each interval follows its point estimate + v_names <- names(x) + expect_equal(match("Lower_95_Inc_Cost", v_names), match("Inc_Cost", v_names) + 1) + expect_identical(attr(x, "ref_str"), "Ref") + expect_s3_class(x, "cers_ref") +}) + +test_that("uncertainty = TRUE gives intervals of the sample-by-sample differences", { + 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) + x <- calculate_cers_ref_psa(psa_big, ref_str = "Surgery", wtp = 50000, uncertainty = TRUE) + i_chemo <- which(cancer_psa_data$strategies == "Chemo") + i_surg <- which(cancer_psa_data$strategies == "Surgery") + r <- row_of(x, "Chemo") + d_cost <- cancer_psa_data$cost[[i_chemo]] - cancer_psa_data$cost[[i_surg]] + d_eff <- cancer_psa_data$effectiveness[[i_chemo]] - cancer_psa_data$effectiveness[[i_surg]] + expect_equal(r$Lower_95_Inc_Cost, unname(quantile(d_cost, 0.025))) + expect_equal(r$Upper_95_Inc_Cost, unname(quantile(d_cost, 0.975))) + expect_equal(r$Lower_95_Inc_Effect, unname(quantile(d_eff, 0.025))) + expect_equal(r$Upper_95_Inc_NMB, unname(quantile(50000 * d_eff - d_cost, 0.975))) + out <- capture.output(tbl <- print(x)) + expect_match(tbl$Prop_NE[2], "^0\\.[0-9]{3}$") +}) diff --git a/tests/testthat/test_currency.R b/tests/testthat/test_currency.R new file mode 100644 index 0000000..ef984d0 --- /dev/null +++ b/tests/testthat/test_currency.R @@ -0,0 +1,54 @@ +# 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(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) + 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 (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 (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, ")")) +}) + +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(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 013d06a..41751f5 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_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") +}) diff --git a/tests/testthat/test_reference_plots.R b/tests/testthat/test_reference_plots.R new file mode 100644 index 0000000..f0101e4 --- /dev/null +++ b/tests/testthat/test_reference_plots.R @@ -0,0 +1,125 @@ +# incremental plane and WTP lines in plot.icers(), plot.psa() and plot.cers_ref() (#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(incremental = TRUE) puts the first non-dominated strategy at the origin", { + # "Cheaper" (cost 50, effect 1.5) is the least costly strategy on the frontier + p <- plot(x_toy, incremental = TRUE) + d <- point_layer(p) + expect_setequal(d$x, df_toy$effect - 1.5) + expect_setequal(d$y, df_toy$cost - 50) + expect_equal(p$labels$y, "Incremental Cost ($)") + expect_equal(p$labels$x, "Incremental Effect (QALYs)") + expect_match(p$labels$caption, "Origin: Cheaper", fixed = TRUE) + # the frontier and statuses do not change + expect_equal(table(d$shape), table(point_layer(plot(x_toy))$shape)) + expect_error(plot(x_toy, incremental = "yes"), "TRUE or FALSE") + expect_false("ref_str" %in% names(formals(plot.icers))) +}) + +test_that("plot.icers(wtp = ) draws the WTP line through the least costly frontier strategy", { + p_abs <- plot(x_toy, wtp = 150) + i <- abline_layers(p_abs) + expect_length(i, 1) + d <- ggplot2::layer_data(p_abs, i) + expect_equal(d$slope, 150) + expect_equal(d$intercept, 50 - 150 * 1.5) + expect_match(p_abs$labels$caption, "WTP = $150/QALY", fixed = TRUE) + + p_inc <- plot(x_toy, incremental = TRUE, wtp = 150) + expect_equal(ggplot2::layer_data(p_inc, abline_layers(p_inc))$intercept, 0) +}) + +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, 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) +}) + +# plot.cers_ref(): the star around the reference strategy +segment_layers <- function(p) { + which(vapply(p$layers, function(l) inherits(l$geom, "GeomSegment"), logical(1))) +} + +test_that("plot.cers_ref() centers the plane at the reference and draws the star", { + x_ref <- calculate_cers_ref(df_toy$cost, df_toy$effect, df_toy$strategy, + ref_str = "Standard of care", wtp = 150) + p <- plot(x_ref) + expect_s3_class(p, "ggplot") + d <- point_layer(p) + others <- df_toy$strategy != "Standard of care" + expect_setequal(d$x, df_toy$effect[others] - 1) + expect_setequal(d$y, df_toy$cost[others] - 100) + expect_length(segment_layers(p), 1) + # the stored threshold draws the WTP line through the origin; NULL removes it + d_wtp <- ggplot2::layer_data(p, abline_layers(p)) + expect_equal(d_wtp$intercept, 0) + expect_equal(d_wtp$slope, 150) + expect_length(abline_layers(plot(x_ref, wtp = NULL)), 0) + expect_match(p$labels$caption, "Reference Strategy (diamond): Standard of care", fixed = TRUE) + expect_length(segment_layers(plot(x_ref, lines = FALSE)), 0) + expect_no_warning(ggplot2::ggplot_build(plot(x_ref, col = "bw", label = "none"))) +}) + +test_that("plot.cers_ref() leaves out the segments for many strategies", { + data(hund_strat) + x_hund <- calculate_cers_ref(hund_strat$Cost, hund_strat$QALYs, hund_strat$Strategy, ref_str = "1") + p <- plot(x_hund, label = "none") + expect_length(segment_layers(p), 0) + expect_length(segment_layers(plot(x_hund, label = "none", lines = TRUE)), 1) + expect_no_warning(ggplot2::ggplot_build(p)) +}) 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) diff --git a/vignettes/basic_cea.Rmd b/vignettes/basic_cea.Rmd index 60a03f9..748e92e 100644 --- a/vignettes/basic_cea.Rmd +++ b/vignettes/basic_cea.Rmd @@ -112,6 +112,13 @@ plot(icer_hiv, ggtitle("Cost-effectiveness of HIV screening strategies") ``` +Decisions are based on incremental costs and effects, so it can help to plot them directly. With `incremental = TRUE`, the costs and effects of every strategy are shown relative to the first non-dominated strategy, the least costly strategy on the frontier (here, the status quo), which is placed at the origin. A willingness-to-pay line (`wtp`) through the origin shows which strategies are cost-effective compared with it at that threshold. +```{r} +plot(icer_hiv, + incremental = TRUE, + wtp = 100000) +``` + *** *** @@ -176,3 +183,32 @@ plot(icer_cdiff, label = "all") # can lead to a 'busy' plot plot(icer_cdiff, plot_frontier_only = TRUE) # completely removes dominated strategies from plot plot(icer_cdiff, currency = "USD", effect_units = "quality-adjusted life-years") # customize axis labels ``` + +*** +*** + +# Comparing every strategy with a reference strategy + +When more than two strategies are compared, health technology assessment guidelines require the fully incremental (sequential) analysis that `calculate_icers()` performs: dominated and extendedly dominated strategies are removed, and each remaining strategy is compared with the next less costly one on the frontier. This is the case in the guidelines of Canada's CDA-AMC ([2017](https://www.cda-amc.ca/sites/default/files/pdf/guidelines_for_the_economic_evaluation_of_health_technologies_canada_4th_ed.pdf)), England's NICE ([2022](https://www.nice.org.uk/process/pmg36/chapter/economic-evaluation-2)), and the Netherlands' Zorginstituut Nederland ([2024](https://english.zorginstituutnederland.nl/documents/2024/01/16/guideline-for-economic-evaluations-in-healthcare)). + +Some settings also call for comparing each strategy with a single reference strategy, such as the current standard of care. NICE, for example, states that "pairwise comparisons may be presented when relevant and justified (for example, when the technology is expected to specifically displace individual comparators)". These comparisons complement the fully incremental analysis; they do not replace it. + +`calculate_cers_ref()` compares every strategy with a reference strategy given in `ref_str`. For each strategy, it gives the difference in cost and effect from the reference, the cost-effectiveness ratio (CER) of that difference, and its status relative to the reference (dominant, dominated, or in one of the two quadrants where a ratio is meaningful). The reference is listed first, followed by the other strategies in order of increasing cost. With `wtp`, the net monetary benefit and its difference from the reference are added. Using the HIV screening example, with the status quo as the reference: +```{r} +cers_hiv <- calculate_cers_ref(cost = v_hiv_costs, + effect = v_hiv_qalys, + strategies = v_hiv_strat_names, + ref_str = "status quo", + wtp = 100000) +cers_hiv +``` + +Compared with the status quo, every screening strategy is more costly and more effective, so each has a CER. Annual screening has a CER below $100,000 per QALY and so looks cost-effective compared with the status quo, yet the fully incremental analysis above shows that it is strongly dominated by screening every 3 years, which costs less and gives more QALYs. This is why the comparison with a reference does not replace the fully incremental analysis. + +The `plot()` method draws the incremental cost-effectiveness plane centered at the reference strategy, with a segment from the reference to each strategy. The willingness-to-pay line stored in the object goes through the origin: strategies below it are cost-effective compared with the reference at that threshold. +```{r} +plot(cers_hiv) +``` + +With many strategies, the segments are left out by default; `lines = TRUE` or `lines = FALSE` overrides this. For a PSA, `calculate_cers_ref_psa()` makes the same comparison from the mean costs and effects, and with `uncertainty = TRUE` adds 95% intervals for the differences and the proportion of PSA samples in each quadrant of the incremental plane. `plot.psa()` with `ref_str` shows the PSA samples themselves on the incremental plane. +