content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' @rdname contour #' #' @template args-he #' @template args-graph #' @template args-pos #' @template args-comparison #' @param ... Additional graphical arguments. The usual ggplot2 syntax is used regardless of graph type. #' \itemize{ #' \item `xlim`: The range of the plot along the x-axis. If NULL (default) it is #' determined by the range of the simulated values for `delta_e` #' \item `ylim`: The range of the plot along the y-axis. If NULL (default) it is #' determined by the range of the simulated values for `delta_c` #' \item `scale`: Scales the plot as a function of the observed standard deviation. #' \item `levels`: Numeric vector of levels at which to draw contour lines. Quantiles 0<p<1. #' \item `nlevels`: Number of levels to be plotted in the contour. #' } #' #' @importFrom stats sd #' @importFrom graphics par #' #' @export #' contour.bcea <- function(he, pos = c(0, 1), graph = c("base", "ggplot2"), comparison = NULL, ...) { graph_type <- match.arg(graph) he <- setComparisons(he, comparison) params <- prep_contour_params(he, ...) if (is_baseplot(graph_type)) { contour_base(he, pos_legend = pos, params, ...) } else if (is_ggplot(graph_type)) { contour_ggplot(he, pos_legend = pos, params, ...) } } #' @title Contour Plots for the Cost-Effectiveness Plane #' #' @description Contour method for objects in the class `bcea`. #' Produces a scatterplot of the cost-effectiveness plane, with a contour-plot #' of the bivariate density of the differentials of cost (y-axis) and #' effectiveness (x-axis). #' #' @template args-he #' #' @return \item{ceplane}{ A ggplot object containing the plot. Returned only #' if `graph="ggplot2"`. } Plots the cost-effectiveness plane with a #' scatterplot of all the simulated values from the (posterior) bivariate #' distribution of (\eqn{\Delta_e, \Delta_c}), the differentials of effectiveness and #' costs; superimposes a contour of the distribution and prints the estimated #' value of the probability of each quadrant (combination of positive/negative #' values for both \eqn{\Delta_e} and \eqn{\Delta_c}) #' #' @author Gianluca Baio, Andrea Berardi #' @references #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @seealso [bcea()], #' [ceplane.plot()], #' [contour2()] #' @keywords hplot #' #' @import ggplot2 #' @importFrom MASS kde2d #' @importFrom grid unit #' @importFrom Rdpack reprompt #' #' @examples #' data(Vaccine) #' #' # run the health economic evaluation using BCEA #' m <- bcea(e=eff, #' c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e,c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000, # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0,Kmax) #' plot=TRUE # plots the results #' ) #' #' contour(m) #' contour(m, graph = "ggplot2") #' #' contour(m, # uses the results of the economic evaluation #' # (a "bcea" object) #' comparison=1, # if more than 2 interventions, selects the #' # pairwise comparison #' nlevels=10, # selects the number of levels to be #' # plotted (default=4) #' levels=NULL, # specifies the actual levels to be plotted #' # (default=NULL, so that R will decide) #' scale=1, # scales the bandwidths for both x- and #' # y-axis (default=0.5) #' graph="base" # uses base graphics to produce the plot #' ) #' #' # use the smoking cessation dataset #' data(Smoking) #' m <- bcea(eff, cost, ref = 4, intervention = treats, Kmax = 500, plot = FALSE) #' contour(m) #' contour(m, graph = "ggplot2") #' #' @export #' contour <- function(he, ...) { UseMethod('contour', he) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/contour.R
#' @rdname contour2 #' @importFrom stats sd #' @importFrom graphics par contour #' #' @export #' contour2.bcea <- function(he, comparison = NULL, wtp = 25000, graph = c("base", "ggplot2"), pos = c(0, 1), ...) { graph_type <- match.arg(graph) he <- setComparisons(he, comparison) params <- prep_contour_params(he, ...) if (is_baseplot(graph_type)) { # encode characters so that the graph can # be saved as postscript or pdf ps.options(encoding = "CP1250") pdf.options(encoding = "CP1250") plot_params <- contour_base_params(he, params) ceplane.plot(he, comparison = NULL, wtp = wtp, pos = pos, graph = "base", ...) add_contours(he, plot_params) } else if (is_ggplot(graph_type)) { plot_params <- contour_ggplot_params(he, params, ...) ceplane.plot(he, comparison = NULL, wtp = wtp, pos = pos, graph = "ggplot2", ...) + do.call(geom_density_2d, plot_params$contour) } } #' Specialised CE-plane Contour Plot #' #' Produces a scatterplot of the cost-effectiveness plane, with a contour-plot #' of the bivariate density of the differentials of cost (y-axis) and #' effectiveness (x-axis). Also adds the sustainability area (i.e. below the #' selected value of the willingness-to-pay threshold). #' #' @template args-he #' @param comparison The comparison being plotted. Default to `NULL` #' If `graph_type="ggplot2"` the default value will choose all the possible #' comparisons. Any subset of the possible comparisons can be selected (e.g., #' `comparison=c(1,3)`). #' @param wtp The selected value of the willingness-to-pay. Default is #' `25000`. #' @template args-graph #' @template args-pos #' @param ... Arguments to be passed to [ceplane.plot()]. See the #' relative manual page for more details. #' #' @return \item{contour}{ A ggplot item containing the requested plot. #' Returned only if `graph_type="ggplot2"`. } Plots the cost-effectiveness #' plane with a scatterplot of all the simulated values from the (posterior) #' bivariate distribution of (\eqn{\Delta_e, \Delta_c}), the differentials of #' effectiveness and costs; superimposes a contour of the distribution and #' prints the value of the ICER, together with the sustainability area. #' @author Gianluca Baio, Andrea Berardi #' @seealso [bcea()], #' [ceplane.plot()], #' [contour()] #' #' @references #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords hplot #' @import ggplot2 #' @importFrom grDevices ps.options pdf.options #' @importFrom MASS kde2d #' @importFrom Rdpack reprompt #' #' @examples #' ## create the bcea object m for the smoking cessation example #' data(Smoking) #' m <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) #' #' ## produce the plot #' contour2(m, #' wtp = 200, #' graph_type = "base") #' #' \donttest{ #' ## or use ggplot2 to plot multiple comparisons #' contour2(m, #' wtp = 200, #' ICER_size = 2, #' graph_type = "ggplot2") #' } #' #' ## vaccination example #' data(Vaccine) #' treats = c("Status quo", "Vaccination") #' m <- bcea(eff, cost, ref = 2, interventions = treats, Kmax = 50000) #' contour2(m) #' contour2(m, wtp = 100) #' #' @rdname contour2 #' @export #' contour2 <- function(he, ...) { UseMethod('contour2', he) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/contour2.R
#' Contour ggplot Parameters #' #' @template args-he #' @param graph_params Other graphical parameters #' @param ... Additional arguments #' #' @import ggplot2 #' @keywords internal #' contour_ggplot_params <- function(he, graph_params, ...) { ext_params <- ceplane_geom_params(...) graph_params$legend <- make_legend_ggplot(he, graph_params$pos_legend) if (!is.null(graph_params$nlevels)) { nlevels <- round(graph_params$nlevels) if (graph_params$nlevels < 0) nlevels <- 10 if (graph_params$nlevels == 0) nlevels <- 1 } default_params <- list( quadrant = quadrant_params(he, graph_params), size = rel(3.5), contour = list( aes_string(colour = "comparison"), contour_var = "ndensity", adjust = 2, size = 1, bins = 5), icer = list( data = data.frame(x = colMeans(he$delta_e), y = colMeans(he$delta_c)), mapping = aes(x = .data$x, y = .data$y), color = "red", size = convert_pts_to_mm(0.8), inherit.aes = FALSE), point = list( shape = rep(19, he$n_comparisons), size = 4), line = list( color = "black")) params <- modifyList(default_params, graph_params) %>% modifyList(ext_params) params$quad_txt <- data.frame( x = c(params$xlim[2], params$xlim[1], params$xlim[1], params$xlim[2]), y = c(params$ylim[2], params$ylim[2], params$ylim[1], params$ylim[1]), label = c(params$quadrant$t1, params$quadrant$t2, params$quadrant$t3, params$quadrant$t4), hjust = c(1, 0, 0, 1)) params }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/contour_ggplot_params.R
#' Contour Cost-Effectiveness Plane #' #' Choice of base R, \pkg{ggplot2}. #' @name contour_graph #' @seealso [contour()] NULL #' Contour Plot Base R Version #' @rdname contour_graph #' #' @template args-he #' @param pos_legend Legend position #' @param graph_params Plot parameters; list #' @param ... Additional arguments #' contour_base <- function(he, pos_legend, graph_params, ...) { extra_args <- list(...) plot_params <- contour_base_params(he, graph_params) legend_params <- ceplane_legend_base(he, pos_legend, plot_params) add_ceplane_setup(plot_params) add_ceplane_points(he, plot_params) add_axes() add_ceplane_legend(legend_params) add_contour_quadrants(he, plot_params) add_contours(he, plot_params) } #' Contour Plot ggplot2 Version #' @rdname contour_graph #' #' @template args-he #' @param pos_legend Legend position #' @param graph_params Plot parameters; list #' @param ... Additional arguments #' #' @import ggplot2 #' @importFrom grid unit #' @importFrom dplyr mutate #' @importFrom reshape2 melt #' contour_ggplot <- function(he, pos_legend, graph_params, ...) { extra_args <- list(...) plot_params <- contour_ggplot_params(he, graph_params, ...) theme_add <- purrr::keep(list(...), is.theme) # single long format for ggplot data delta_ce <- merge( melt( cbind(sim = seq_len(nrow(he$delta_c)), he$delta_c), variable.name = "comparison", value.name = "delta_c", id.vars = "sim"), melt( cbind(sim = seq_len(nrow(he$delta_e)), he$delta_e), variable.name = "comparison", value.name = "delta_e", id.vars = "sim"), by = c("sim", "comparison")) %>% mutate(comparison = factor(.data$comparison)) ggplot(delta_ce, aes(x = .data$delta_e, y = .data$delta_c, group = .data$comparison, col = .data$comparison, shape = .data$comparison)) + geom_point(size = plot_params$point$size) + do.call(geom_density_2d, plot_params$contour) + geom_quad_txt(he, plot_params) + geom_hline(yintercept = 0, colour = "grey") + geom_vline(xintercept = 0, colour = "grey") + ceplane_legend_manual(he, plot_params) + coord_cartesian(xlim = plot_params$xlim, ylim = plot_params$ylim, expand = TRUE) + do.call(labs, list(title = plot_params$title, x = plot_params$xlab, y = plot_params$ylab)) + do.call(theme, plot_params$legend) + theme_contour() + theme_add }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/contour_graph.R
#' Use from Base R to ggplot #' #' @param x points #' @keywords internal #' convert_pts_to_mm <- function(x) x*72.27/25.4
/scratch/gouwar.j/cran-all/cranData/BCEA/R/convert_pts_to_mm.R
# Package: ldr # Type: Package # Title: Methods for likelihood-based dimension reduction in regression # Version: 1.3.3 # Date: 2014-06-06 # Author: Kofi Placid Adragni, Andrew Raim # Maintainer: Kofi Placid Adragni <[email protected]> # Description: Functions, methods, and data sets for fitting likelihood-based dimension reduction in regression, # using principal fitted components (pfc), likelihood acquired directions (lad), covariance reducing models (core). # URL: https://www.jstatsoft.org/v61/i03/ # License: GPL (>= 2) # Packaged: 2021-10-08 16:32:42 UTC; Nathan # Repository: https://github.com/cran/ldr # Date/Publication: 2014-10-29 16:36:14 # # Covariance Reduction # # Method to reduce sample covariance matrices to an informational core that is sufficient to # characterize the variance heterogeneity among different populations. # #' @importFrom stats cov #' @importFrom utils tail #' core <- function(X, y, Sigmas=NULL, ns=NULL, numdir=2, numdir.test=FALSE, ...) { mf <- match.call() if (!is.null(Sigmas)) { if (is.null(ns)) stop("Number of observations per class must be provided") p <- dim(Sigmas[[1]])[1]; hlevels <- length(Sigmas) } if (is.null(Sigmas) & is.null(ns)) { if (is.factor(y)) y <- as.integer(y) hlevels <- length(unique(y)); p <- ncol(X) Sigmas <-list(); ns <- vector(length=hlevels) for (h in 1:hlevels) { ns[h] <- sum(y==h) Sigmas[[h]] <- cov(as.matrix(X[y==h,], ncol=p)) } } n <- sum(ns); ff <- ns/n; d <- numdir if (!numdir.test) { fit <- one.core(d, p, hlevels, ff, Sigmas, ns, ...) ans <- list(Gammahat=fit$Gammahat, Sigmahat = fit$Sigmahat, Sigmashat = fit$Sigmashat, loglik=fit$loglik, aic=fit$aic, bic=fit$bic, numpar=fit$numpar, numdir=d, model="core", call=match.call(expand.dots = TRUE), numdir.test=numdir.test) class(ans) <- "core" return(invisible(ans)) } aic <- bic <- numpar <- loglik <- vector(length=d+1) Gammahat <- Sigmahat <- Sigmashat <- list() loglik <- numpar <- aic <- bic <- numeric(d+1) for (i in 0:d) { if (!is.null(mf$verbose)) cat("Running CORE for numdir =", i, "\n") fit <- one.core(i, p, hlevels, ff, Sigmas, ns, ...) Gammahat[[i+1]] <-fit$Gammahat Sigmahat[[i+1]] <- fit$Sigmahat Sigmashat[[i+1]] <- fit$Sigmashat loglik[i+1] <- fit$loglik numpar[i+1] <- fit$numpar aic[i+1] <- fit$aic bic[i+1] <- fit$bic } ans <- list(Gammahat=Gammahat, Sigmahat = Sigmahat, Sigmashat = Sigmashat, loglik=loglik, aic=aic, bic=bic, numpar=numpar, numdir=d, model="core", call=match.call(expand.dots = TRUE), numdir.test=numdir.test) class(ans) <- "core" return(invisible(ans)) } #' one.core <- function(d, p, hlevels, ff, Sigmas, ns, ...) { if (d == 0) { Gamma.hat <- NULL Sigma.hat <- matrix(0, p, p) for (g in 1:hlevels) {Sigma.hat <- Sigma.hat + ff[g] * Sigmas[[g]]} term0 <- 0 term1 <- n/2 * log(det(Sigma.hat)) loglik <- term0 - term1 } else if (d == p) { Gamma.hat <- diag(p) Sigma.hat <- matrix(0, p, p) for (g in 1:hlevels){Sigma.hat <- Sigma.hat + ff[g] * Sigmas[[g]]} term0 <- 0 term1 <- n/2 * log(det(Sigma.hat)) term2 <- n/2 * log(det(Sigma.hat)) term3 <- 0 for (g in 1:hlevels){term3 <- term3 + ns[g]/2 * log(det(Sigmas[[g]]))} loglik <- Re(term0 - term1 + term2 - term3) } else { objfun <- function(W) { Q <- W$Qt; d <- W$dim[1]; p <- W$dim[2] Sigmas <- W$Sigmas n <- sum(W$ns) U <- matrix(Q[,1:d], ncol=d) V <- matrix(Q[,(d+1):p], ncol=(p-d)) Sigma.hat <- matrix(0, p, p) for (g in 1:hlevels){Sigma.hat <- Sigma.hat + ff[g] * Sigmas[[g]]} Ps <- projection(U, diag(p)) # Objective function term0 <- 0 term1 <- n/2 * log(det(Sigma.hat)) term2 <- n/2 * log(det(t(U) %*% Sigma.hat %*% U)) term3 <- 0 for (g in 1:hlevels){term3 <- term3 + ns[g]/2 * log(det(t(U) %*% Sigmas[[g]] %*% U))} value <- Re(term0 - term1 + term2 - term3) return(list(value=value)) } objfun <- assign("objfun", objfun, envir=.BaseNamespaceEnv) W <- list(dim=c(d, p), Sigmas=Sigmas, ns=ns) grassmann <- GrassmannOptim(objfun, W, ...) Gamma.hat <- matrix(grassmann$Qt[,1:d], ncol = d) loglik <- tail(grassmann$fvalues, n = 1) } Sigma.hat <- matrix(0, p, p) for (g in 1:hlevels){Sigma.hat <- Sigma.hat + ff[g] * Sigmas[[g]]} if (d != 0){Ps.hat <- projection(Gamma.hat, Sigma.hat)} Sigmas.hat <- list() for (g in 1:hlevels) { if (d == 0) { Sigmas.hat[[g]] <- Sigma.hat } else { Sigmas.hat[[g]] <- Sigma.hat + t(Ps.hat) %*% ( Sigmas[[g]] - Sigma.hat) %*% Ps.hat } } numpar <- p*(p+1)/2 + d*(p-d) + (hlevels-1)*d*(d+1)/2 aic <- -2*loglik + 2 * numpar bic <- -2*loglik + log(n) * numpar return(list(Gammahat=Gamma.hat, Sigmahat = Sigma.hat, Sigmashat = Sigmas.hat, loglik=loglik, numpar=numpar, aic=aic, bic=bic)) } # projection <- function(alpha, Sigma) { return(alpha %*% solve(t(alpha) %*% Sigma %*% alpha) %*% t(alpha) %*% Sigma) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/core.R
#' Data set for the Bayesian model for the cost-effectiveness of smoking #' cessation interventions #' #' This data set contains the results of the Bayesian analysis used to model #' the clinical output and the costs associated with the health economic #' evaluation of four different smoking cessation interventions. #' #' @name Smoking #' @docType data #' @aliases Smoking cost data eff life.years pi_post smoking smoking_output treats #' @format A data list including the variables needed for the smoking cessation #' cost-effectiveness analysis. The variables are as follows: #' \describe{ #' \item{list("cost")}{a matrix of 500 simulations from the posterior distribution #' of the overall costs associated with the four strategies} #' \item{list("data")}{a dataset containing the characteristics of the smokers #' in the UK population} #' \item{list("eff")}{a matrix of 500 simulations from the #' posterior distribution of the clinical benefits associated with the four #' strategies} #' \item{list("life.years")}{a matrix of 500 simulations from the #' posterior distribution of the life years gained with each strategy} #' \item{list("pi_post")}{a matrix of 500 simulations from the posterior #' distribution of the event of smoking cessation with each strategy} #' \item{list("smoking")}{a data frame containing the inputs needed for the #' network meta-analysis model. The `data.frame` object contains: #' `nobs`: the record ID number, `s`: the study ID number, `i`: #' the intervention ID number, `r_i`: the number of patients who quit #' smoking, `n_i`: the total number of patients for the row-specific arm #' and `b_i`: the reference intervention for each study} #' \item{list("smoking_mat")}{a matrix obtained by running the network #' meta-analysis model based on the data contained in the `smoking` object} #' \item{list("treats")}{a vector of labels associated with the four strategies} #' } #' @references Baio G. (2012). Bayesian Methods in Health Economics. CRC/Chapman Hall, London #' #' @source Effectiveness data adapted from Hasselblad V. (1998). Meta-analysis #' of Multitreatment Studies. Medical Decision Making 1998;18:37-43. #' Cost and population characteristics data adapted from various sources: #' \itemize{ #' \item Taylor, D.H. Jr, et al. (2002). Benefits of smoking #' cessation on longevity. American Journal of Public Health 2002;92(6) #' \item ASH: Action on Smoking and Health (2013). ASH fact sheet on smoking #' statistics, \cr `https://ash.org.uk/files/documents/ASH_106.pdf` #' \item Flack, S., et al. (2007). Cost-effectiveness of interventions for smoking #' cessation. York Health Economics Consortium, January 2007 #' \item McGhan, W.F.D., and Smith, M. (1996). Pharmacoeconomic analysis of #' smoking-cessation interventions. American Journal of Health-System Pharmacy #' 1996;53:45-52} #' @keywords datasets NULL #' Data set for the Bayesian model for the cost-effectiveness of influenza #' vaccination #' #' This data set contains the results of the Bayesian analysis used to model #' the clinical output and the costs associated with an influenza vaccination. #' #' @name Vaccine #' @docType data #' @aliases Vaccine c.pts cost.GP cost.hosp cost.otc cost.time.off cost.time.vac #' cost.travel cost.trt1 cost.trt2 cost.vac e.pts N N.outcomes N.resources #' QALYs.adv QALYs.death QALYs.hosp QALYs.inf QALYs.pne vaccine vaccine_mat #' @format A data list including the variables needed for the influenza #' vaccination. The variables are as follows: #' \describe{ #' \item{list("cost")}{a matrix of simulations from the posterior #' distribution of the overall costs associated with the two treatments} #' \item{list("c.pts")}{} #' \item{list("cost.GP")}{a matrix of simulations from the posterior #' distribution of the costs for GP visits associated with the two treatments} #' \item{list("cost.hosp")}{a matrix of simulations from the posterior #' distribution of the costs for hospitalisations associated with the two #' treatments} #' \item{list("cost.otc")}{a matrix of simulations from the posterior distribution #' of the costs for over-the-counter medications associated with the two treatments} #' \item{list("cost.time.off")}{a matrix of simulations from the posterior #' distribution of the costs for time off work associated with the two treatments} #' \item{list("cost.time.vac")}{a matrix of simulations from the posterior #' distribution of the costs for time needed to get the vaccination associated #' with the two treatments} #' \item{list("cost.travel")}{a matrix of simulations from the posterior #' distribution of the costs for travel to get vaccination associated with the #' two treatments} #' \item{list("cost.trt1")}{a matrix of simulations from the #' posterior distribution of the overall costs for first line of treatment #' associated with the two interventions} #' \item{list("cost.trt2")}{a matrix of simulations from the posterior distribution #' of the overall costs for second line of treatment associated with the two #' interventions} #' \item{list("cost.vac")}{a matrix of simulations from the posterior #' distribution of the costs for vaccination} #' \item{list("eff")}{a matrix of simulations from the posterior distribution of #' the clinical benefits associated with the two treatments} #' \item{list("e.pts")}{} #' \item{list("N")}{the number of subjects in the reference population} #' \item{list("N.outcomes")}{the number of clinical outcomes analysed} #' \item{list("N.resources")}{the number of health-care resources under study} #' \item{list("QALYs.adv")}{a vector from the posterior distribution of the #' QALYs associated with advert events} #' \item{list("QALYs.death")}{a vector from the posterior distribution of the #' QALYs associated with death} #' \item{list("QALYs.hosp")}{a vector from the posterior distribution of the #' QALYs associated with hospitalisation} #' \item{list("QALYs.inf")}{a vector from the posterior distribution of the #' QALYs associated with influenza infection} #' \item{list("QALYs.pne")}{a vector from the posterior distribution of the #' QALYs associated with pneumonia} #' \item{list("treats")}{a vector of labels associated with the two treatments} #' \item{list("vaccine_mat")}{a matrix containing the simulations for the #' parameters used in the original model} #' } #' @references Baio, G., Dawid, A. P. (2011). Probabilistic Sensitivity #' Analysis in Health Economics. Statistical Methods in Medical Research #' doi:10.1177/0962280211419832. #' @source Adapted from Turner D, Wailoo A, Cooper N, Sutton A, Abrams K, #' Nicholson K. The cost-effectiveness of influenza vaccination of healthy #' adults 50-64 years of age. Vaccine. 2006;24:1035-1043. #' @keywords datasets NULL
/scratch/gouwar.j/cran-all/cranData/BCEA/R/data.R
#' Diagnostic Plots For The Results Of The EVPPI #' #' The function produces either a residual plot comparing the fitted #' values from the INLA-SPDE Gaussian Process regression to the residuals. #' This is a scatter plot of residuals on the y axis and fitted values (estimated #' responses) on the x axis. The plot is used to detect non-linearity, unequal #' error variances, and outliers. A well-behaved residual plot supporting the #' appropriateness of the simple linear regression model has the following #' characteristics: #' 1) The residuals bounce randomly around the 0 line. This suggests that #' the assumption that the relationship is linear is reasonable. #' 2) The residuals roughly form a horizontal band around the 0 line. This #' suggests that the variances of the error terms are equal. #' 3) None of the residual stands out from the basic random pattern of residuals. #' This suggests that there are no outliers. #' #' The second possible diagnostic is the Q-Q plot for the fitted value. This is a #' graphical method for comparing the fitted values distributions with the #' assumed underlying normal distribution by plotting their quantiles against #' each other. First, the set of intervals for the quantiles is chosen. A point #' (x,y) on the plot corresponds to one of the quantiles of the second #' distribution (y-coordinate) plotted against the same quantile of the first #' distribution (x-coordinate). If the two distributions being compared are #' identical, the Q-Q plot follows the 45 degrees line. #' #' @param evppi A `evppi` object obtained by running the function `evppi` #' on a `bcea` model. #' @template args-he #' @param plot_type The type of diagnostics to be performed. It can be the 'residual #' plot' (`residuals`) or the Q-Q (quantile-quantile) plot (`qqplot`). #' @param interv Specifies the interventions for which diagnostic tests should be #' performed (if there are many options being compared) #' @return Plot #' #' @author Gianluca Baio, Anna Heath #' @seealso [bcea()], [evppi()] #' @importFrom Rdpack reprompt #' #' @references #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords internal hplot #' @export #' diag.evppi <- function(evppi, he, plot_type = c("residuals", "qqplot"), interv = 1) { if (interv > 1 && dim(evppi$fitted.costs)[2] == 1) { stop("There is only one comparison possible, so 'interv' set to 1 (default)", call. = FALSE)} plot_type <- match.arg(plot_type) is_residual <- pmatch(plot_type, c("residuals", "qqplot")) != 2 if (is_residual) { evppi_residual_plot(evppi, he, interv) } else { evppi_qq_plot(evppi, he, interv) } } #' Residual Plot #' @keywords internal hplot #' evppi_residual_plot <- function(evppi, he, interv) { fitted <- list(cost = evppi$fitted.costs[, interv], eff = evppi$fitted.effects[, interv]) residual <- list(cost = as.matrix(he$delta_c)[evppi$select, interv] - fitted$cost, eff = as.matrix(he$delta_e)[evppi$select, interv] - fitted$eff) cex <- 0.8 op <- par(mfrow = c(1, 2)) plot(fitted$cost, residual$cost, xlab = "Fitted values", ylab = "Residuals", main = "Residual plot for costs", cex = cex) abline(h = 0) plot(fitted$eff, residual$eff, xlab = "Fitted values", ylab = "Residuals", main = "Residual plot for effects", cex = cex) abline(h = 0) par(op) } #' Q-Q Plot #' @keywords internal hplot #' #' @importFrom graphics par #' @importFrom stats qqnorm qqline #' evppi_qq_plot <- function(evppi, he, interv) { op <- par(mfrow = c(1, 2)) fit_cost <- evppi$fitted.costs[, interv] fit_eff <- evppi$fitted.effects[, interv] qqnorm(fit_cost, main = "Normal Q-Q plot \n(costs)") qqline(fit_cost) qqnorm(fit_eff, main = "Normal Q-Q plot \n(effects)") qqline(fit_eff) par(op) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/diag.evppi.R
#' @rdname eib.plot #' #' @importFrom graphics lines abline text legend #' @import ggplot2 #' #' @template args-he #' @template args-comparison #' @template args-pos #' @param size Value (in millimetres) of the size of the willingness to pay #' label. Used only if `graph="ggplot2"`, otherwise it will be ignored #' with a message. If set to `NA`, the break-even point line(s) and #' label(s) are suppressed, with both base graphics and ggplot2. #' @param plot.cri Logical value. Should the credible intervals be plotted #' along with the expected incremental benefit? Default as `NULL` draws #' the 95\% credible intervals if only one comparison is selected, and does not #' include them for multiple comparisons. Setting `plot.cri=TRUE` or #' `plot.cri=FALSE` forces the function to add the intervals or not. The #' level of the intervals can be also set, see \ldots{} for more details. #' @template args-graph #' @param ... If `graph="ggplot2"` and a named theme object is supplied, #' it will be added to the ggplot object. Additional arguments: #' \itemize{ #' \item `alpha` can be used to set the CrI level when `plot.cri=TRUE`, #' with a default value of `alpha=0.05`. #' \item `cri.quantile` controls the the method of calculation of the credible #' intervals. The default value `cri.quantile=TRUE` defines the CrI as the #' interval between the `alpha/2`-th and `1-alpha/2`-th quantiles of #' the IB distribution. Setting `cri.quantile=FALSE` will use a normal #' approximation on the IB distribution to calculate the intervals. #' \item `currency`: Currency prefix to willingness to pay values - ggplot2 only. #' \item `line_colors`: specifies the line colour(s) - all graph types. #' \item `line_types`: specifies the line type(s) as lty numeric values - all graph types. #' \item `area_include`: include area under the EIB curve - plotly only. #' \item `area_color`: specifies the AUC curve - plotly only.} #' #' @export #' eib.plot.bcea <- function(he, comparison = NULL, pos = c(1, 0), size = NULL, plot.cri = NULL, graph = c("base", "ggplot2", "plotly"), ...) { graph <- match.arg(graph) he <- setComparisons(he, comparison) graph_params <- c(prep_eib_params(he, plot.cri, ...), list(pos = pos, size = size, plot.cri = plot.cri)) if (is_baseplot(graph)) { eib_plot_base(he, graph_params, ...) } else if (is_ggplot(graph)) { eib_plot_ggplot(he, graph_params, ...) } else if (is_plotly(graph)) { eib_plot_plotly(he, graph_params, ...) } } #' @title Expected Incremental Benefit (EIB) Plot #' #' @description Produces a plot of the Expected Incremental Benefit (EIB) as a function of #' the willingness to pay. #' #' @template args-he #' @param ... If `graph="ggplot2"` and a named theme object is supplied, #' it will be added to the ggplot object. Additional arguments: #' \itemize{ #' \item `alpha` can be used to set the CrI level when `plot.cri=TRUE`, #' with a default value of `alpha=0.05`. #' \item `cri.quantile` controls the the method of calculation of the credible #' intervals. The default value `cri.quantile=TRUE` defines the CrI as the #' interval between the `alpha/2`-th and `1-alpha/2`-th quantiles of #' the IB distribution. Setting `cri.quantile=FALSE` will use a normal #' approximation on the IB distribution to calculate the intervals. #' \item `line = list(color)`: specifies the line colour(s) - all graph types. #' \item `line = list(type)`: specifies the line type(s) as lty numeric values - all graph types. #' \item `area_include`: include area under the EIB curve - plotly only. #' \item `area_color`: specifies the AUC curve - plotly only.} #' #' @return \item{eib}{ If `graph="ggplot2"` a ggplot object, or if `graph="plotly"` #' a plotly object containing the requested plot. Nothing is returned when `graph="base"`, #' the default.} The function produces a plot of the #' Expected Incremental Benefit as a function of the discrete grid #' approximation of the willingness to pay parameter. The break even point #' (i.e. the point in which the EIB = 0, i.e. when the optimal decision changes #' from one intervention to another) is also showed by default. The value `k*` is #' the discrete grid approximation of the ICER. #' #' @author Gianluca Baio, Andrea Berardi #' @seealso [bcea()], #' [ib.plot()], #' [ceplane.plot()] #' @references #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords hplot #' @import ggplot2 #' @importFrom grid unit #' @importFrom Rdpack reprompt #' #' @export #' #' @examples #' data(Vaccine) #' #' # Runs the health economic evaluation using BCEA #' m <- bcea( #' e=eff, #' c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e, c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000, # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0, Kmax) #' plot=FALSE # plots the results #' ) #' eib.plot(m) #' eib.plot(m, graph = "ggplot2") + ggplot2::theme_linedraw() #' #' data(Smoking) #' treats <- c("No intervention", "Self-help", #' "Individual counselling", "Group counselling") #' m <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) #' eib.plot(m) #' eib.plot <- function(he, ...) { UseMethod('eib.plot', he) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/eib.plot.R
#' eib_legend_base <- function(he, graph_params) { list(x = where_legend(he, graph_params$pos), legend = paste0(he$interventions[he$ref], " vs ", he$interventions[he$comp]), cex = 0.7, bty = "n", lwd = graph_params$line$lwd, col = graph_params$line$color, lty = graph_params$line$type) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/eib_legend_base.R
#' EIB parameters specific to base R plot #' #' @template args-he #' @param graph_params Type of plot device #' @param cri_params Credible interval parameters #' @return list #' @keywords internal #' eib_params_base <- function(he, graph_params, cri_params) { ylim <- if (!cri_params$plot.cri) { range(c(he$eib)) } else { range(c(he$eib), cri_params$data$low, cri_params$data$upp) } list( xlab = graph_params$xlab, ylab = graph_params$ylab, main = graph_params$main, col = graph_params$line$color, lwd = graph_params$line$lwd, lty = graph_params$line$type, type = "l", xlim = range(he$k), ylim = ylim) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/eib_params_base.R
#' EIB Parameters CrI #' @keywords internal aplot #' eib_params_cri <- function(he, graph_params) { list(plot.cri = graph_params$plot.cri, data = compute_eib_cri(he, graph_params$alpha_cri, graph_params$cri.quantile), col = graph_params$line$cri_col, lty = graph_params$line$cri_lty) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/eib_params_cri.R
# eib_params_ggplot <- function(he, graph_params, cri_params, ...) { graph_params <- helper_ggplot_params(he, graph_params) ##TODO: remove duplication with base ylim <- if (!cri_params$plot.cri) { range(c(he$eib)) } else { range(c(he$eib), cri_params$data) } default_params <- list( size = rel(3.5), kstar = list( geom = "text", label = paste0("k* = ", format(he$kstar, digits = 6)), x = he$kstar, y = min(ylim), hjust = ifelse((max(he$k) - he$kstar)/max(he$k) > 1/6, yes = -0.1, no = 1.1), vjust = 1), cri = list( lwd = ifelse(!graph_params$plot.cri, 0.5, 0.75), show.legend = FALSE), currency = "") modifyList(default_params, graph_params) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/eib_params_ggplot.R
#' Expected Incremental Benefit Plot By Graph Device #' #' Choice of base R, ggplot2 or plotly. #' @name eib_plot_graph #' NULL #' EIB plot base R version #' @rdname eib_plot_graph #' #' @template args-he #' @param graph_params List of graph parameters #' @param ... Additional arguments #' eib_plot_base <- function(he, graph_params, ...) { cri_params <- eib_params_cri(he, graph_params) plot_params <- eib_params_base(he, graph_params, cri_params) legend_params <- eib_legend_base(he, graph_params) do.call(matplot, c(list(x = he$k, y = he$eib), plot_params), quote = TRUE) abline(h = 0, col = "grey") # x-axis plot_eib_cri(he, cri_params) # credible intervals kstar_vlines(he, plot_params) do.call(legend, legend_params) } #' EIB plot ggplot2 version #' @rdname eib_plot_graph #' #' @template args-he #' @param graph_params Graph parameters #' @param ... Additional parameters #' #' @import ggplot2 #' @importFrom grid unit #' @importFrom purrr keep #' @importFrom scales label_dollar #' eib_plot_ggplot <- function(he, graph_params, ...) { extra_params <- list(...) ##TODO: can we move this up a level? cri_params <- eib_params_cri(he, graph_params) theme_add <- purrr::keep(extra_params, is.theme) legend_params <- make_legend_ggplot(he, graph_params$pos) graph_params <- eib_params_ggplot(he, graph_params, cri_params) data_psa <- data.frame( k = c(he$k), eib = c(he$eib), comparison = as.factor(rep(1:he$n_comparison, each = length(he$k)))) ggplot(data_psa, aes(x = .data$k, y = .data$eib, group = .data$comparison)) + geom_line(aes(colour = .data$comparison, linetype = .data$comparison)) + theme_eib() + theme_add + do.call(theme, legend_params) + do.call(labs, list(title = graph_params$main, x = graph_params$xlab, y = graph_params$ylab)) + geom_hline(aes(yintercept = 0), colour = "grey", linetype = 1) + geom_cri(graph_params$plot.cri, cri_params) + do.call(annotate, graph_params$kstar) + scale_x_continuous( labels = scales::label_dollar(prefix = graph_params$currency)) + geom_vline( aes(xintercept = .data$kstar), data = data.frame("kstar" = he$kstar), colour = "grey50", linetype = 2, linewidth = 0.5) + scale_linetype_manual( "", labels = graph_params$labels, values = graph_params$line$type) + scale_colour_manual( "", labels = graph_params$labels, values = graph_params$line$color) } #' EIB plot plotly version #' @rdname eib_plot_graph #' #' @template args-he #' @param graph_params Graph parameters #' @param ... Additional parameters #' eib_plot_plotly <- function(he, graph_params, ...) { cri_params <- eib_params_cri(he, graph_params) alt.legend <- graph_params$alt.legend plot_aes <- graph_params$plot_aes plot_annotations <- graph_params$plot_annotations plot.cri <- graph_params$plot.cri cri.quantile <- graph_params$cri.quantile comparison <- graph_params$comparison alpha <- graph_params$alpha_cri cri <- graph_params$cri size <- graph_params$size main <- graph_params$main xlab <- graph_params$xlab ylab <- graph_params$ylab low <- cri_params$data$low upp <- cri_params$data$upp if (!is.null(size) && !is.na(size)) { message("Option size will be ignored using plotly.") size <- NULL } if (he$n_comparisons > 1 && !is.null(comparison)) { # adjusts bcea object for the correct number of dimensions and comparators he$comp <- he$comp[comparison] he$delta_e <- he$delta_e[, comparison] he$delta_c <- he$delta_c[, comparison] he$n_comparators <- length(comparison) + 1 he$n_comparisons <- length(comparison) he$interventions <- he$interventions[sort(c(he$ref, he$comp))] he$ICER <- he$ICER[comparison] he$ib <- he$ib[, , comparison] he$eib <- he$eib[, comparison] he$U <- he$U[, , sort(c(he$ref, comparison + 1))] he$ceac <- he$ceac[, comparison] he$ref <- rank(c(he$ref, he$comp))[1] he$comp <- rank(c(he$ref, he$comp))[-1] he$change_comp <- TRUE return( eib.plot( he, pos = alt.legend, graph = "plotly", size = size, comparison = NULL, plot.cri = plot.cri, alpha = alpha, cri.quantile = cri.quantile, ...)) } n_comp <- length(comparison) plot_aes$line$types <- plot_aes$line$types %||% rep(1:6, ceiling(he$n_comparisons/6))[1:he$n_comparisons] comparisons.label <- paste0(he$interventions[he$ref], " vs ", he$interventions[he$comp]) if (length(plot_aes$line$types) < n_comp) plot_aes$line$types <- rep_len(plot_aes$line$types, n_comp) if (length(plot_aes$line$colors) < n_comp) plot_aes$line$colors <- rep_len(plot_aes$line$colors, n_comp) # opacities plot_aes$line$cri_colors <- sapply(plot_aes$line$cri_colors, function(x) ifelse(grepl(pattern = "^rgba\\(", x = x), x, plotly::toRGB(x, 0.4))) plot_aes$area$color <- sapply(plot_aes$area$color, function(x) ifelse(grepl(pattern = "^rgba\\(", x = x), x, plotly::toRGB(x, 0.4))) data.psa <- data.frame( k = he$k, eib = c(he$eib), comparison = as.factor(c( sapply(1:he$n_comparisons, function(x) rep(x, length(he$k))) )), label = as.factor(c( sapply(comparisons.label, function(x) rep(x, length(he$k))) ))) if (plot.cri) data.psa <- cbind(data.psa, cri) eib <- plotly::plot_ly(data.psa, x = ~k) eib <- plotly::add_trace( eib, y = ~eib, type = "scatter", mode = "lines", fill = ifelse(plot_aes$area$include, "tozeroy", "none"), name = ~label, fillcolor = plot_aes$area$color, color = ~comparison, colors = plot_aes$line$colors, linetype = ~comparison, linetypes = plot_aes$line$types, legendgroup = ~comparison) # decision change points not included # hover functionality is sufficient if (plot.cri) { if (he$n_comparisons == 1) { eib <- plotly::add_ribbons( eib, name = paste0(100 * (1 - alpha), "% CrI"), ymin = ~low, ymax = ~upp, color = NA, fillcolor = ~plot_aes$line$cri_colors[comparison]) } else { eib <- plotly::add_ribbons( eib, name = ~label, ymin = ~low, ymax = ~upp, line = list(color = plot_aes$line$cri_colors[1]), # for transparency, use plotly::toRGB("blue", alpha = 0.5) legendgroup = ~comparison, fillcolor = "rgba(1, 1, 1, 0)", linetype = ~comparison, linetypes = plot_aes$line$types, showlegend = FALSE) } } # legend positioning not great # must be customized case by case legend_list <- list(orientation = "h", xanchor = "center", x = 0.5) if (is.character(alt.legend)) legend_list <- switch( alt.legend, "left" = list(orientation = "v", x = 0, y = 0.5), "right" = list(orientation = "v", x = 0, y = 0.5), "bottom" = list(orienation = "h", x = 0.5, y = 0, xanchor = "center"), "top" = list(orientation = "h", x = 0.5, y = 100, xanchor = "center")) xaxis <- list( hoverformat = ".2f", title = xlab) yaxis <- list( hoverformat = ".2f", title = ylab) eib <- plotly::layout( eib, title = main, xaxis = xaxis, yaxis = yaxis, showlegend = TRUE, legend = legend_list) plotly::config(eib, displayModeBar = FALSE) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/eib_plot_graph.R
#' @rdname evi.plot #' #' @template args-he #' @param graph A string used to select the graphical engine to use for #' plotting. Should (partial-)match the three options `"base"`, #' `"ggplot2"` or `"plotly"`. Default value is `"base"`. #' @param ... Additional parameters #' #' @return \item{eib}{ If `graph="ggplot2"` a ggplot object, or if `graph="plotly"` #' a plotly object containing the requested plot. Nothing is returned when `graph="base"`, #' the default.} The function produces a plot of the #' Expected Value of Information as a function of the discrete grid #' approximation of the willingness to pay parameter. The break even point(s) #' (i.e. the point in which the EIB=0, ie when the optimal decision changes #' from one intervention to another) is(are) also showed. #' @author Gianluca Baio, Andrea Berardi #' @seealso [bcea()], #' [ceac.plot()], #' [ceplane.plot()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords hplot #' @export #' #' @examples #' data(Vaccine) #' m <- bcea( #' e=eff, #' c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e, c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000, # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0, Kmax) #' plot=FALSE # plots the results #' ) #' evi.plot(m) #' #' data(Smoking) #' treats <- c("No intervention", "Self-help", #' "Individual counselling", "Group counselling") #' m <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) #' evi.plot(m) #' evi.plot.bcea <- function(he, graph = c("base", "ggplot2", "plotly"), ...) { graph <- match.arg(graph) extra_args <- list(...) plot_annotations <- list("exist" = list("title" = FALSE, "xlab" = FALSE, "ylab" = FALSE)) plot_aes <- list("area" = list("include" = TRUE, "color" = "grey50"), "line" = list("colors" = "black", "types" = NULL)) plot_aes_args <- c("area_include", "area_color", "line_colors", "line_types") ##TODO: should we be using this? plot_aes$cri.quantile <- TRUE if (length(extra_args) >= 1) { # if existing, read and store title, xlab and ylab for (annotation in names(plot_annotations$exist)) { if (exists(annotation, where = extra_args)) { plot_annotations$exist[[annotation]] <- TRUE plot_annotations[[annotation]] <- extra_args[[annotation]] } } # if existing, read and store graphical options for (aes_arg in plot_aes_args) { if (exists(aes_arg, where = extra_args)) { aes_cat <- strsplit(aes_arg, "_")[[1]][1] aes_name <- paste0(strsplit(aes_arg, "_")[[1]][-1], collapse = "_") plot_aes[[aes_cat]][[aes_name]] <- extra_args[[aes_arg]] } } } if (!plot_annotations$exist$title) plot_annotations$title <- "Expected Value of Information" if (!plot_annotations$exist$xlab) plot_annotations$xlab <- "Willingness to pay" if (!plot_annotations$exist$ylab) plot_annotations$ylab <- "EVPI" data.psa <- data.frame(k = c(he$k), evi = c(he$evi)) if (is_baseplot(graph)) { evi_plot_base(he, data.psa, plot_aes, plot_annotations) } else if (is_ggplot(graph)) { evi_plot_ggplot(he, data.psa, plot_aes, plot_annotations) } else if (is_plotly(graph)) { evi_plot_plotly(data.psa, plot_aes, plot_annotations) } } #' Expected Value of Information (EVI) Plot #' #' Plots the Expected Value of Information (EVI) against the willingness to pay. #' #' @template args-he #' @param ... Additional graphical arguments: #' \itemize{ #' \item `line_colors` to specify the EVPI line colour - all graph types. #' \item `line_types` to specify the line type (lty) - all graph types. #' \item `area_include` to specify whether to include the area under the #' EVPI curve - plotly only. #' \item `area_color` to specify the area under the colour curve - plotly only.} #' #' @export #' evi.plot <- function(he, ...) { UseMethod('evi.plot', he) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/evi.plot.R
#' EVI Plot of the Health Economic Analysis For Mixed Analysis #' #' Compares the optimal scenario to the mixed case in terms of the EVPI. #' #' @param he An object of class `mixedAn`, a subclass of `bcea`, #' given as output of the call to the function [mixedAn()]. #' @param y.limits Range of the y-axis for the graph. The default value is #' `NULL`, in which case the maximum range between the optimal and the #' mixed analysis scenarios is considered. #' @template args-pos #' @param graph A string used to select the graphical engine to use for #' plotting. Should (partial-)match the two options `"base"` or #' `"ggplot2"`. Default value is `"base"`. #' @param ... Arguments to be passed to methods, such as graphical parameters #' (see [par()]). #' #' @return \item{evi}{ A ggplot object containing the plot. Returned only if #' `graph="ggplot2"`. } The function produces a graph showing the #' difference between the ''optimal'' version of the EVPI (when only the most #' cost-effective intervention is included in the market) and the mixed #' strategy one (when more than one intervention is considered in the market). #' #' @author Gianluca Baio, Andrea Berardi #' @seealso [bcea()], #' [mixedAn()] #' @import ggplot2 #' @importFrom grid unit #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2009}{BCEA} #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @examples #' # See Baio G., Dawid A.P. (2011) for a detailed description of the #' # Bayesian model and economic problem #' # #' # Load the processed results of the MCMC simulation model #' data(Vaccine) #' #' # Runs the health economic evaluation using BCEA #' m <- bcea(e=eff, c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e,c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000, # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0,Kmax) #' plot=FALSE # inhibits graphical output #' ) #' #' mixedAn(m) <- NULL # uses the results of the mixed strategy #' # analysis (a "mixedAn" object) #' # the vector of market shares can be defined #' # externally. If NULL, then each of the T #' # interventions will have 1/T market share #' # produces the plots #' evi.plot(m) #' #' evi.plot(m, graph="base") #' #' # Or with ggplot2 #' if (require(ggplot2)) { #' evi.plot(m, graph="ggplot2") #' } #' #' @export #' evi.plot.mixedAn <- function(he, y.limits = NULL, pos = c(0, 1), graph = c("base", "ggplot2"), ...) { alt_legend <- pos base.graphics <- all(pmatch(graph, c("base", "ggplot2")) != 2) y.limits <- y.limits %||% range(he$evi, he$evi.star) if (base.graphics) { if (is.numeric(alt_legend) && length(alt_legend) == 2) { temp <- "" if (alt_legend[2] == 0) temp <- paste0(temp,"bottom") else temp <- paste0(temp,"top") if (alt_legend[1] == 1) temp <- paste0(temp, "right") else temp <- paste0(temp, "left") alt_legend <- temp if (length(grep("^(bottom|top)(left|right)$", temp)) == 0) alt_legend <- FALSE } if (is.logical(alt_legend)) { alt_legend <- if (!alt_legend) "topright" else "topleft" } plot(he$k, he$evi, type = "l", xlab = "Willingness to pay", ylab = "EVPI", main = "Expected Value of Information", ylim = y.limits) polygon(c(he$k, rev(he$k)), c(he$evi.star, rev(he$evi)), density = 20, col = "grey") points(he$k, he$evi.star, type = "l", col = "red") points(he$k, he$evi, type = "l", col = "black") txt <- c( "Optimal strategy", "Mixed strategy:", paste( " ", he$interventions, "=", format(100 * he$mkt.shares, digits = 3, nsmall = 2), "%", sep = "")) cols <- c("black", "red", rep("white", length(he$interventions))) legend( alt_legend, txt, col = cols, cex = 0.6, bty = "n", lty = 1) } else { # base.graphics if (!isTRUE(requireNamespace("ggplot2", quietly = TRUE) && requireNamespace("grid", quietly = TRUE))) { message("Falling back to base graphics\n") evi.plot.mixedAn(he, y.limits = y.limits, pos = pos, graph = "base") return(invisible(NULL)) } if (isTRUE(requireNamespace("ggplot2", quietly = TRUE) && requireNamespace("grid", quietly = TRUE))) { # legend txt <- c("Optimal strategy", paste0("Mixed strategy:", paste0("\n ",he$interventions,"=", format(100*he$mkt.shares, digits = 3, nsmall = 2), "%", collapse = ""))) colours <- c("black","red") df <- data.frame("k" = he$k, "evi" = he$evi, "evi.star" = he$evi.star) evi <- ggplot(df, aes(x = .data$k)) + theme_bw() + geom_ribbon(aes(x = .data$k, ymin = .data$evi, ymax = .data$evi.star), colour = "lightgrey", alpha = 0.2) + geom_line(aes(x = .data$k, y = .data$evi, colour = as.factor(1))) + geom_line(aes(x = .data$k, y = .data$evi.star, colour = as.factor(2))) + coord_cartesian(ylim = y.limits, xlim = c(0, max(df$k))) + scale_colour_manual("", labels = txt, values = colours) + labs(title = "Expected Value of Information", x = "Willingness to pay", y = "EVPI") + theme( text = element_text(size = 11), legend.key.size = unit(0.66, "lines"), legend.spacing = unit(-1.25, "line"), panel.grid = element_blank(), legend.key = element_blank(), plot.title = element_text(face = "bold", hjust = 0.5)) jus <- NULL if (isTRUE(alt_legend)) { alt_legend <- "bottom" evi <- evi + theme(legend.direction = "vertical") } else { if (is.character(alt_legend)) { choices <- c("left", "right", "bottom", "top") alt_legend <- choices[pmatch(alt_legend,choices)] jus <- "center" if (is.na(alt_legend)) alt_legend <- FALSE } if (length(alt_legend) > 1) jus <- alt_legend if (length(alt_legend) == 1 && !is.character(alt_legend)) { alt_legend <- c(0,1) jus <- alt_legend } } evi <- evi + theme( legend.position = alt_legend, legend.justification = jus, legend.title = element_blank(), legend.background = element_blank(), legend.text.align = 0, plot.title = element_text( lineheight = 1.05, face = "bold", size = 14.3, hjust = 0.5)) return(evi) } } }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/evi.plot.mixedAn.R
#' Expected Value of Information Plot By Graph Device #' #' Choice of base R, \pkg{ggplot2} or \pkg{plotly}. #' @name evi_plot_graph #' NULL #' EVI plot base R version #' @rdname evi_plot_graph #' #' @template args-he #' @param data.psa Data #' @param plot_aes Aesthetic parameters #' @param plot_annotations Plot parameters #' evi_plot_base <- function(he, data.psa, plot_aes, plot_annotations) { plot( x = data.psa$k, y = data.psa$evi, type = "l", xlab = plot_annotations$xlab, ylab = plot_annotations$ylab, main = plot_annotations$title, col = plot_aes$line$colors, lty = ifelse(is.null(plot_aes$line$types), 1, plot_aes$line$type)) pts_lty <- 2 pts_col <- "dark grey" if (length(he$kstar) == 1) { points( x = rep(he$kstar, 3), y = c(-10000, he$evi[he$k == he$kstar] / 2, he$evi[he$k == he$kstar]), type = "l", lty = pts_lty, col = pts_col) points(x = c(-10000, he$kstar / 2, he$kstar), y = rep(he$evi[he$k == he$kstar], 3), type = "l", lty = pts_lty, col = pts_col) } if (length(he$kstar) > 1) { for (i in seq_along(he$kstar)) { points( x = rep(he$kstar[i], 3), y = c(-10000, he$evi[he$k == he$kstar[i]] / 2, he$evi[he$k == he$kstar[i]]), type = "l", lty = pts_lty, col = pts_col) points( x = c(-10000, he$kstar[i] / 2, he$kstar[i]), y = rep(he$evi[he$k == he$kstar[i]], 3), type = "l", lty = pts_lty, col = pts_col) } } } #' EVI plot ggplot version #' @rdname evi_plot_graph #' #' @template args-he #' @param data.psa Data #' @param plot_aes Aesthetic parameters #' @param plot_annotations Plot parameters #' #' @import ggplot2 grid #' evi_plot_ggplot <- function(he, data.psa, plot_aes, plot_annotations) { evi <- ggplot(data.psa, aes(.data$k, .data$evi)) + geom_line( colour = plot_aes$line$colors, lty = ifelse(is.null(plot_aes$line$types), 1, plot_aes$line$type)) + theme_bw() + labs(title = plot_annotations$title, x = plot_annotations$xlab, y = plot_annotations$ylab) if (length(he$kstar) != 0) { kstars <- length(he$kstar) evi.at.kstar <- numeric(kstars) for (i in seq_len(kstars)) { evi.at.kstar[i] <- he$evi[which.min(abs(he$k - he$kstar[i]))] } for (i in seq_len(kstars)) { evi <- evi + annotate( "segment", x = he$kstar[i], xend = he$kstar[i], y = evi.at.kstar[i], yend = -Inf, linetype = 2, colour = "grey50") + annotate( "segment", x = he$kstar[i], xend = -Inf, y = evi.at.kstar[i], yend = evi.at.kstar[i], linetype = 2, colour = "grey50") } } evi + theme(text = element_text(size = 11), legend.key.size = grid::unit(0.66, "lines"), legend.spacing = grid::unit(-1.25, "line"), panel.grid = element_blank(), legend.key = element_blank(), plot.title = element_text( lineheight = 1.05, face = "bold", size = 14.3, hjust = 0.5)) } #' EVI plot plotly version #' @rdname evi_plot_graph #' #' @param data.psa Data #' @param plot_aes Aesthetic parameters #' @param plot_annotations Plot parameters #' evi_plot_plotly <- function(data.psa, plot_aes, plot_annotations) { plot_aes$area$color <- sapply(plot_aes$area$color, function(x) ifelse(grepl(pattern = "^rgba\\(", x = x), x, plotly::toRGB(x, 0.4))) legend_list <- list(orientation = "h", xanchor = "center", x = 0.5) # actual plot evi <- plotly::plot_ly(data.psa, x = ~k) evi <- plotly::add_trace( evi, y = ~evi, type = "scatter", mode = "lines", name = "EVPI", fill = ifelse(plot_aes$area$include, "tozeroy", "none"), fillcolor = plot_aes$area$color, line = list( color = plot_aes$line$colors[1], dash = c("solid", "dot", "dash", "longdash", "dashdot", "longdashdot")[ ifelse(is.null(plot_aes$line$types), 1, plot_aes$line$types)])) evi <- plotly::layout( evi, title = plot_annotations$title, xaxis = list( hoverformat = ".2f", title = plot_annotations$xlab), yaxis = list( hoverformat = ".2f", title = plot_annotations$ylab), # legend hidden by default (single series) showlegend = FALSE, legend = legend_list) plotly::config(evi, displayModeBar = FALSE) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/evi_plot_graph.R
#' Expected Value of Perfect Partial Information (EVPPI) for Selected #' Parameters #' #' Calculates the Expected Value of Perfect Partial Information (EVPPI) for #' subsets of parameters. Uses GAM non-parametric regression for single #' parameter EVPPI and the SPDE-INLA method for larger parameter subsets. #' #' The single parameter EVPPI has been calculated using the non-parametric GAM #' regression developed by Strong *et al.* (2014). The multi-parameter EVPPI is #' calculated using the SPDE-INLA regression method for Gaussian Process #' regression developed by Heath *et al.* (2015). #' #' This function has been completely changed and restructured to make it possible #' to change regression method. #' The method argument can now be given as a list. The first element element in the #' list is a vector giving the regression method for the effects. The second gives #' the regression method for the costs. The `method' argument can also be given as #' before which then uses the same regression method for all curves. #' All other `extra_args` can be given as before. `int.ord` can be updated using the #' list formulation above to give the interactions for each different curve. #' The formula argument for GAM can only be given once, either `te()` or `s() + s()` #' as this is for computational reasons rather than to aid fit. #' You can still plot the INLA mesh elements but not output the meshes. #' #' @aliases evppi evppi.default #' @param param_idx A vector of parameters for which the EVPPI should be #' calculated. This can be given as a string (or vector of strings) of names or #' a numeric vector, corresponding to the column numbers of important #' parameters. #' @param input A matrix containing the simulations for all the parameters #' monitored by the call to JAGS or BUGS. The matrix should have column names #' matching the names of the parameters and the values in the vector parameter #' should match at least one of those values. #' @template args-he #' @param N The number of PSA simulations used to calculate the EVPPI. The #' default uses all the available samples. #' @param plot A logical value indicating whether the triangular mesh for #' SPDE-INLA should be plotted. Default set to `FALSE`. #' @param residuals A logical value indicating whether the fitted values for #' the SPDE-INLA method should be outputted. Default set to `TRUE`. #' @param method Character string to select which method to use. The default methods are recommended. #' However, it is possible (mainly for backward compatibility) to use different methods. #' @param ... Additional arguments. Details of the methods to compute the EVPPI and their additional arguments are: #' - For single-parameter: #' - Generalized additive model (GAM) (default). #' - The method of Strong & Oakley use `method` as string `so`. #' The user *needs* to also specify the number of "blocks" (e.g. `n.blocks=20`). #' Note that the multi-parameter version for this method has been deprecated. #' - The method of Sadatsafavi *et al.* where `method` takes as value a string of either `sad` or `sal`. #' It is then possible to also specify the number of "separators" (e.g. `n.seps=3`). #' If none is specified, the default value `n.seps=1` is used. #' Note that the multi-parameter version for this method has been deprecated. #' - For multi-parameter: #' - INLA/SPDE (default). #' - Gaussian process regression with `method` of `gp`. #' #' @section GAM regression: #' For multi-parameter, the user can select 3 possible methods. If #' `method = "GAM"` (BCEA will accept also `"gam"`, `"G"` or #' `"g"`), then the computations are based on GAM regression. The user can #' also specify the formula for the regression. The default option is to use a #' tensor product (e.g. if there are two main parameters, `p1` and #' `p2`, this amounts to setting `formula = "te(p1,p2)"`, which #' indicates that the two parameters interact). Alternatively, it is possible #' to specify a model in which the parameters are independent using the #' notation `formula = "s(p1) + s(p2)"`. This may lead to worse accuracy in #' the estimates. #' #' @section Strong *et al.* GP regression: #' This is used if `method="GP"` (BCEA will also accept the specification #' `method="gp"`). In this case, the user can also specify the number of #' PSA runs that should be used to estimate the hyperparameters of the model #' (e.g. `n.sim=100`). This value is set by default to 500. #' #' @section INLA-related options: #' These are all rather technical and are described in detail in Baio *et al.* (2017). #' The optional parameter vector `int.ord` can take integer values (c(1,1) is #' default) and will force the predictor to include interactions: if #' `int.ord = c(k, h)`, then all k-way interactions will be used for the #' effects and all h-way interactions will be used for the costs. Also, the #' user can specify the feature of the mesh for the "spatial" part of the #' model. The optional parameter `cutoff` (default 0.3) controls the #' density of the points inside the mesh. Acceptable values are typically in #' the interval (0.1, 0.5), with lower values implying more points (and thus #' better approximation and greater computational time). The construction of the #' boundaries for the mesh can be controlled by the optional inputs #' `convex.inner` (default = -0.4) and `convex.outer` (default = #' -0.7). These should be negative values and can be decreased (say to -0.7 and #' -1, respectively) to increase the distance between the points and the outer #' boundary, which also increases precision and computational time. The #' optional argument`robust` can be set to TRUE, in which case INLA will #' use a t prior distribution for the coefficients of the linear predictor. #' Finally, the user can control the accuracy of the INLA grid-search for the #' estimation of the hyperparameters. This is done by setting a value #' `h.value` (default = 0.00005). Lower values imply a more refined search #' (and hence better accuracy), at the expense of computational speed. The #' method argument can also be given as a list allowing different regression #' methods for the effects and costs, and the different incremental decisions. #' The first list element should contain a vector of methods for the #' incremental effects and the second for the costs, for example #' `method = list(c("GAM"), c("INLA"))`. The `int.ord` argument can also #' be given as a list to give different interaction levels for each regression #' curve. #' #' By default, when no method is specified by the user, `evppi` will #' use GAM if the number of parameters is <5 and INLA otherwise. #' #' @return Object of class `evppi`: #' \item{evppi}{The computed values of evppi for all values of the #' parameter of willingness to pay.} #' \item{index}{A numerical vector with the index associated with the #' parameters for which the EVPPI was calculated.} #' \item{k}{The vector of values for the willingness to pay.} #' \item{evi}{The vector of values for the overall EVPPI.} #' \item{fitted.costs}{The fitted values for the costs.} #' \item{fitted.effects}{The fitted values for the effects.} #' \item{parameters}{A single string containing the names of the #' parameters for which the EVPPI was calculated, used for plotting the EVPPI.} #' \item{time}{Computational time (in seconds).} #' \item{fit.c}{The object produced by the model fit for the costs.} #' \item{fit.e}{The object produced by the model fit for the effects.} #' \item{formula}{The formula used to fit the model.} #' \item{method}{A string indicating the method used to estimate the EVPPI.} #' #' @author Anna Heath, Gianluca Baio #' @seealso [bcea()], #' [plot.evppi()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Strong2014}{BCEA} #' #' \insertRef{Sadatsafavi2013}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' \insertRef{Baio2017}{BCEA} #' #' \insertRef{Heath2016}{BCEA} #' #' @export #' @md #' #' @examples #' # See Baio G., Dawid A.P. (2011) for a detailed description of the #' # Bayesian model and economic problem #' #' \dontrun{ #' # Load the post-processed results of the MCMC simulation model #' # original JAGS output is can be downloaded from here #' # https://gianluca.statistica.it/book/bcea/code/vaccine.RData #' #' data(Vaccine, package = "BCEA") #' treats <- c("Status quo", "Vaccination") #' #' # Run the health economic evaluation using BCEA #' m <- bcea(e.pts, c.pts, ref = 2, interventions = treats) #' #' # Compute the EVPPI for a bunch of parameters #' inp <- createInputs(vaccine_mat) #' #' EVPPI <- evppi(m, c("beta.1." , "beta.2."), inp$mat) #' #' plot(EVPPI) #' #' # deprecated (single parameter) methods #' EVPPI.so <- evppi(m, c("beta.1.", "beta.2."), inp$mat, method = "so", n.blocks = 50) #' EVPPI.sad <- evppi(m, c("beta.1.", "beta.2."), inp$mat, method = "sad", n.seps = 1) #' #' plot(EVPPI.so) #' plot(EVPPI.sad) #' #' # Compute the EVPPI using INLA/SPDE #' if (require("INLA")) #' x_inla <- evppi(he = m, 39:40, input = inp$mat) #' #' # using GAM regression #' x_gam <- evppi(he = m, 39:40, input = inp$mat, method = "GAM") #' #' # using Strong et al GP regression #' x_gp <- evppi(he = m, 39:40, input = inp$mat, method = "GP") #' #' # plot results #' if (require("INLA")) plot(x_inla) #' points(x_inla$k, x_inla$evppi, type = "l", lwd = 2, lty = 2) #' points(x_gam$k, x_gam$evppi, type = "l", col = "red") #' points(x_gp$k, x_gp$evppi, type = "l", col = "blue") #' #' if (require("INLA")) { #' plot(x_inla$k, x_inla$evppi, type = "l", lwd = 2, lty = 2) #' points(x_gam$k, x_gam$evppi, type = "l", col = "red") #' points(x_gp$k, x_gp$evppi, type = "l", col = "blue") #' } #' #' data(Smoking) #' treats <- c("No intervention", "Self-help", #' "Individual counselling", "Group counselling") #' m <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) #' inp <- createInputs(smoking_output) #' EVPPI <- evppi(m, c(2,3), inp$mat, h.value = 0.0000005) #' plot(EVPPI) #' } #' evppi <- function(he, param_idx, input, N = NULL, plot = FALSE, residuals = TRUE, ...) UseMethod("evppi", he)
/scratch/gouwar.j/cran-all/cranData/BCEA/R/evppi.R
#' @rdname evppi #' @export #' evppi.default <- function(he, ...) { stop("No method available", call. = FALSE) } #' @rdname evppi #' #' @examples #' data(Vaccine, package = "BCEA") #' treats <- c("Status quo", "Vaccination") #' bcea_vacc <- bcea(e.pts, c.pts, ref = 2, interventions = treats) #' inp <- createInputs(vaccine_mat) #' evppi(bcea_vacc, c("beta.1.", "beta.2."), inp$mat) #' @export #' evppi.bcea <- function(he, param_idx = NULL, input, N = NULL, plot = FALSE, residuals = TRUE, method = NULL, ...) { if (!requireNamespace("voi", quietly = TRUE)) { stop( "Package \"voi (>= 1.0.1)\" must be installed to use this function.", call. = FALSE ) } comp_ids <- c(he$comp, he$ref) outputs <- list(e = he$e[, comp_ids], c = he$c[, comp_ids], k = he$k) if (!is.null(method)) method <- tolower(method) # allow alternative name for Sadatsafavi method if (length(method) > 0 && method == "sad") method <- "sal" # replace column numbers with names pars <- if (all(is.numeric(param_idx))) { if (any(!param_idx %in% 1:ncol(input))) stop("Column number(s) not in available parameter inputs") param_idx <- names(input)[param_idx] } else { param_idx } n_sims <- nrow(input) n_outputs <- nrow(outputs$c) # this way passes on error checking to voi::evppi if (n_sims == n_outputs) { # subset number of PSA samples; default all row_idxs <- if (is.null(N) || (N >= n_sims)) { 1:n_sims } else { sample(1:n_sims, size = N, replace = FALSE) } input <- data.frame(input[row_idxs, ]) outputs$e <- outputs$e[row_idxs, ] outputs$c <- outputs$c[row_idxs, ] } res <- voi::evppi(outputs, inputs = input, pars = pars, method = method, check = TRUE, plot_inla_mesh = plot, ...) voi_methods <- unname(attr(res, "methods")) voi_models <- attr(res, "models") # method name returned from evppi method_nm <- voi_methods[1] form <- if (method_nm == "gam") { paste("te(", paste(param_idx, ",", sep = "", collapse = ""), "bs='cr')") } else {NULL} has_fitted_values <- residuals && (method_nm %in% c("inla", "gp", "gam")) if (has_fitted_values) { fitted_c <- get_fitted_("c", voi_methods, voi_models) fitted_e <- get_fitted_("e", voi_methods, voi_models) } else { fitted_c <- NULL fitted_e <- NULL } residuals_out <- list(fitted.costs = fitted_c, fitted.effects = fitted_e, select = row_idxs) out <- c( list( evppi = res$evppi, index = pars, k = res$k, evi = he$evi, parameters = paste(pars, collapse = " and "), time = list("Fitting for Effects" = NULL, "Fitting for Costs" = NULL, "Calculating EVPPI" = NULL), method = list("Methods for Effects" = voi_methods, "Methods for Costs" = voi_methods)), residuals_out, list(formula = form, pars = res$pars, res = res)) structure(out, class = c("evppi", class(out))) } #' Get fitted values from evppi object #' #' @importFrom purrr list_cbind map #' @keywords internal #' @return matrix # get_fitted_ <- function(val, voi_methods, voi_models) { method_nm <- voi_methods[1] # named differently in different methods fitted_lup <- c(inla = "fitted", gp = "fitted", gam = "fitted.values") fitted_txt <- fitted_lup[method_nm] fitted_ls <- purrr::map(voi_models[[1]][[val]], ~unname(as.data.frame(.x[[fitted_txt]]))) |> rev() suppressMessages( purrr::list_cbind(fitted_ls)) |> as.matrix() |> cbind(0) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/evppi.default.R
#' @title Plot Expected Value of Partial Information With Respect to a #' Set of Parameters #' #' @description Base R and \pkg{ggplot2} versions. #' #' @name evppi_plot_graph #' NULL #' @rdname evppi_plot_graph #' #' @param evppi_obj Object of class `evppi` #' @param pos_legend Position of legend #' @param col Colour #' @param annot Annotate EVPPI curve with parameter names #' evppi_plot_base <- function(evppi_obj, pos_legend, col = NULL, annot = FALSE) { legend_params <- evppi_legend_base(evppi_obj, pos_legend, col) plot(evppi_obj$k, evppi_obj$evi, type = "l", col = legend_params$col[1], lty = legend_params$lty[1], xlab = "Willingness to pay", ylab = "", main = "Expected Value of Perfect Partial Information", lwd = 2, ylim = range(range(evppi_obj$evi), range(evppi_obj$evppi))) if (!is.list(evppi_obj$evppi)) evppi_obj$evppi <- list(evppi_obj$evppi) evppi_dat <- do.call(cbind, evppi_obj$evppi) txt_coord_y <- evppi_dat[length(evppi_obj$k), ] matplot(evppi_obj$k, evppi_dat, type = "l", col = legend_params$col[-1], lty = legend_params$lty[-1], add = TRUE) if (annot) { text(x = par("usr")[2], y = txt_coord_y, labels = paste0("(", evppi_obj$index, ")", collapse = " "), cex = 0.7, pos = 2) } do.call(legend, legend_params) return(invisible(NULL)) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/evppi_plot_base.R
#' @rdname evppi_plot_graph #' #' @param evppi_obj Object of class evppi #' @param pos_legend Position of legend #' @param col Colour #' @param ... Additional arguments #' #' @importFrom purrr pluck keep #' @import dplyr ggplot2 #' evppi_plot_ggplot <- function(evppi_obj, pos_legend = c(0, 0.8), col = c(1,1), ...) { extra_args <- list(...) plot_dat <- evppi_obj[c("evi", "evppi", "k")] %>% bind_rows() %>% ##TODO: for >1 evppi melt(id.vars = "k") %>% mutate(variable = as.character(.data$variable), variable = ifelse(.data$variable == "evppi", paste("EVPPI for", evppi_obj$parameters), "EVPI")) theme_add <- purrr::keep(extra_args, is.theme) size <- purrr::pluck(extra_args, "size", .default = c(1, 0.5)) legend_params <- make_legend_ggplot(evppi_obj, pos_legend) ggplot(plot_dat, aes(x = .data$k, y = .data$value, group = .data$variable, size = .data$variable, colour = .data$variable)) + geom_line() + theme_default() + theme_add + scale_color_manual(values = col) + scale_size_manual(values = size) + do.call(theme, legend_params) + ggtitle("Expected Value of Perfect Partial Information") + xlab("Willingness to pay") + ylab("") }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/evppi_plot_ggplot.R
#' @importFrom grDevices colors #' evppi_legend_cols <- function(evppi_obj, col = NULL) { n_cols <- length(evppi_obj$parameters) + 1 if (is.null(col)) { cols <- colors() gr <- floor(seq(from = 261, to = 336, length.out = n_cols)) return(cols[gr]) } else { if (length(col) != n_cols) { message( "The vector 'col' must have the number of elements for an EVPI colour and each of the EVPPI parameters. Forced to black\n") return(rep("black", length(evppi_obj$parameters) + 1)) } } col } #' evppi_legend_text <- function(evppi_obj) { cmd <- if (nchar(evppi_obj$parameters[1]) <= 25) { paste0("EVPPI for ", evppi_obj$parameters) } else "EVPPI for the selected\nsubset of parameters" if (length(evppi_obj$index) > 1 && (("Strong & Oakley (univariate)" %in% evppi_obj$method) || ("Sadatsafavi et al" %in% evppi_obj$method))) { # label lines for (i in seq_along(evppi_obj$index)) { ##TODO: # text(x = par("usr")[2], # y = evppi_obj$evppi[[i]][length(evppi_obj$k)], # labels = paste0("(", i, ")"), cex = 0.7, pos = 2) } cmd <- paste0("(", paste(seq_len(evppi_obj$index)), ") EVPPI for ", evppi_obj$parameters) } c("EVPI", cmd) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/evppi_plot_helpers.R
# helper functions so don't have to remember # which dimension for which statistic Ustar_filter_by <- function(he, wtp) { he$Ustar[, he$k == wtp] } U_filter_by <- function(he, wtp) { he$U[, he$k == wtp, ] } ib_filter_by <- function(he, wtp) { he$ib[he$k == wtp, , ] } ol_filter_by <- function(he, wtp) { he$ol[, he$k == wtp] } vi_filter_by <- function(he, wtp) { he$vi[, he$k == wtp] }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/filter_by.R
#' Credible interval ggplot geom #' #' @param plot.cri Should we plot CrI? Logical #' @param params Plot parameters including data #' @keywords internal aplot #' geom_cri <- function(plot.cri = TRUE, params = NA) { if (plot.cri) { list(geom_line(data = params$data, aes(y = .data$low, group = .data$comp), linetype = 2), geom_line(data = params$data, aes(y = .data$upp, group = .data$comp), linetype = 2)) } else list(NULL) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/geom_cri.R
#' @importFrom grDevices colors #' @keywords dplot #' helper_base_params <- function(he, graph_params) { n_lines <- num_lines(he) if (n_lines == 1) { default_params <- list(list(lwd = 1, line = list(type = 1))) graph_params <- modifyList(default_params, graph_params) } if (n_lines > 1) { default_params <- list(list(lwd = ifelse(n_lines <= 6, 1, 1.5), line = list(type = rep_len(1:6, n_lines), color = colors()[floor(seq(262, 340, length.out = n_lines))]) )) graph_params <- modifyList(default_params, graph_params) types <- graph_params$line$type cols <- graph_params$line$color is_enough_types <- length(types) >= n_lines || length(types) == 1 is_enough_colours <- length(cols) >= n_lines || length(cols) == 1 if (!is_enough_types) { graph_params$line$type <- rep_len(types, n_lines) message("Wrong number of line types provided. Falling back to default\n")} if (!is_enough_colours) { graph_params$line$color <- rep_len(cols, n_lines) message("Wrong number of colours provided. Falling back to default\n")} } list(type = "l", main = graph_params$annot$title, xlab = graph_params$annot$x, ylab = graph_params$annot$y, ylim = c(0, 1), lty = graph_params$line$type, col = graph_params$line$color, lwd = graph_params$lwd, pch = NULL) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/helper_base_params.R
#' @noRd #' #' @keywords dplot #' helper_ggplot_params <- function(he, graph_params) { n_lines <- num_lines(he) if (n_lines == 1) { default_params <- list(labels = NULL, line = list(type = 1, color = 1, size = 1)) graph_params <- modifyList(default_params, graph_params) } if (n_lines > 1) { default_params <- list(labels = line_labels(he), line = list(type = rep_len(1:6, n_lines), color = 1, size = rep_len(1, n_lines))) graph_params <- modifyList(default_params, graph_params) types <- graph_params$line$type cols <- graph_params$line$color sizes <- graph_params$line$size is_enough_types <- length(types) >= n_lines is_enough_colours <- length(cols) >= n_lines is_enough_sizes <- length(sizes) == n_lines if (!is_enough_types) { graph_params$line$type <- rep_len(types, n_lines)} if (!is_enough_colours) { graph_params$line$color <- rep_len(cols, n_lines)} if (!is_enough_sizes) { graph_params$line$size <- rep_len(sizes, n_lines)} } graph_params }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/helper_ggplot_params.R
#' @rdname ib.plot #' #' @param comparison In the case of multiple interventions, specifies the one #' to be used in comparison with the reference. Default value of `NULL` #' forces R to consider the first non-reference intervention as the comparator. #' Controls which comparator is used when more than 2 interventions are present #' @param wtp The value of the willingness to pay threshold. Default value at #' `25000`. #' @param bw Identifies the smoothing bandwidth used to construct the kernel #' estimation of the IB density. #' @param n The number of equally spaced points at which the density is to be #' estimated. #' @param xlim The limits of the plot on the x-axis. #' @param graph A string used to select the graphical engine to use for #' plotting. Should (partial-) match the two options `"base"` or #' `"ggplot2"`. Default value is `"base"`. #' #' @return \item{ib}{ A ggplot object containing the requested plot. Returned #' only if `graph="ggplot2"`. } The function produces a plot of the #' distribution of the Incremental Benefit for a given value of the willingness #' to pay parameter. The dashed area indicates the positive part of the #' distribution (i.e. when the reference is more cost-effective than the #' comparator). #' @author Gianluca Baio, Andrea Berardi #' @seealso [bcea()], #' [ceplane.plot()] #' @references #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords hplot #' @export #' #' @import ggplot2 #' @importFrom Rdpack reprompt #' #' @examples #' data("Vaccine") #' he <- BCEA::bcea(eff, cost) #' ib.plot(he) #' ib.plot.bcea <- function(he, comparison = NULL, wtp = 25000, bw = "bcv", ##TODO: what was nbw? previous was bigger/smoother n = 512, xlim = NULL, graph = c("base", "ggplot2"), ...) { base.graphics <- all(pmatch(graph, c("base", "ggplot2")) != 2) if (!is.null(comparison)) stopifnot(comparison <= he$n_comparison) if (base.graphics) { ib_plot_base(he, comparison, wtp, bw, n, xlim) } else { ib_plot_ggplot(he, comparison, wtp, bw, n, xlim) } } #' Incremental Benefit (IB) Distribution Plot #' #' Plots the distribution of the Incremental Benefit (IB) for a given value of #' the willingness to pay threshold. #' #' @template args-he #' @param ... Additional arguments #' @export #' ib.plot <- function(he, ...) { UseMethod('ib.plot', he) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/ib.plot.R
#' IB plot base R version #' @rdname ib_plot_graph #' #' @template args-he #' @param comparison Comparison interventions #' @param wtp Willingness to pay #' @param bw Band width #' @param n Number #' @param xlim x-axis limits #' @importFrom stats density #' ib_plot_base <- function(he, comparison, wtp, bw, n, xlim) { if (max(he$k) < wtp) { wtp <- max(he$k) cat(paste("NB: k (wtp) is defined in the interval [", min(he$k)," - ", wtp,"]\n", sep = "")) } if (!is.element(wtp, he$k)) { if (!is.na(he$step)) { # The user has selected a non-acceptable value for wtp, # but has not specified wtp in the call to bcea stop(paste("The willingness to pay parameter is defined in the interval [0-", he$Kmax, "], with increments of ", he$step, "\n", sep = ""), call. = FALSE) } else { # The user has actually specified wtp as input in the call to bcea tmp <- paste(he$k, collapse = " ") stop(paste0("The willingness to pay parameter is defined as:\n [",tmp, "]\n Please select a suitable value", collapse = " "), call. = FALSE) } } w <- which(he$k == wtp) if (he$n_comparisons == 1) { ##TODO: where should this be used? # nbw <- sd(he$ib[w, , 1])/1.5 d <- density(he$ib[w, , 1], bw = bw, n = n) txt <- paste("Incremental Benefit distribution\n", he$interventions[he$ref], " vs ", he$interventions[he$comp], sep = "") } if (he$n_comparisons > 1) { comparison <- comparison %||% 1 # nbw <- sd(he$ib[w, , comparison])/1.5 d <- density(he$ib[w, , comparison], bw = bw, n = n) txt <- paste("Incremental Benefit distribution\n", he$interventions[he$ref], " vs ", he$interventions[he$comp[comparison]], sep = "") } xlim <- xlim %||% range(d$x) plot( d$x, d$y, type = "l", ylab = "Density", xlab = expression(paste("IB(", bold(theta), ")", sep = "")), main = txt, axes = FALSE, col = "white", xlim = xlim) box() axis(1) ypt <- 0.95*max(d$y) xpt <- d$x[max(which(d$y >= ypt))] text(xpt, ypt, parse(text = paste("p(IB(",expression(bold(theta)),")>0,k==", format(wtp, digits = 8, nsmall = 2), ")", sep = "")), cex = 0.85, pos = 4) xplus <- d$x[d$x >= 0] yplus <- d$y[d$x >= 0] polygon(c(0, xplus), c(0, yplus), density = 20, border = "white") points(d$x, d$y, type = "l") abline(v = 0, h = 0, col = "black") }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/ib_plot_base.R
#' Incremental Benefit Plot By Graph Device #' #' Choice of base R, ggplot2 #' @name ib_plot_graph #' NULL #' IB plot ggplot2 version #' @rdname ib_plot_graph #' #' @template args-he #' @param comparison Comparison intervention #' @param wtp Willingness to pay #' @param bw band width #' @param n Number #' @param xlim x-axis limits #' #' @import ggplot2 grid #' @importFrom dplyr filter #' ib_plot_ggplot <- function(he, comparison, wtp, bw, n, xlim) { comparison <- comparison %||% 1 if (max(he$k) < wtp) { wtp <- max(he$k) message( paste0("NB: k (wtp) is defined in the interval [", min(he$k), " - ", wtp, "]\n")) } if (!is.element(wtp, he$k)) { if (!is.na(he$step)) { # The user has selected a non-acceptable value for wtp, # but has not specified wtp in the call to bcea stop( paste("The willingness to pay parameter is defined in the interval [0-", he$Kmax, "], with increments of ", he$step,"\n", sep = ""), call. = FALSE) } else { # The user has actually specified wtp as input in the call to bcea tmp <- paste(he$k, collapse = " ") stop(paste0("The willingness to pay parameter is defined as:\n [", tmp, "]\n Please select a suitable value", collapse = " "), call. = FALSE) } } w <- which(he$k == wtp) if (he$n_comparisons == 1) { ##TODO: where should this be used? # nbw <- sd(he$ib[w, , 1])/1.5 density <- density(he$ib[w, ,1], bw = bw, n = n) df <- data.frame(x = density$x, y = density$y) } if (he$n_comparisons > 1) { # nbw <- sd(he$ib[w, , comparison])/1.5 density <- density(he$ib[w, , comparison], bw = bw, n = n) df <- data.frame(x = density$x, y = density$y) } xlim <- xlim %||% range(df$x) ib <- ggplot(df, aes(.data$x, .data$y)) + theme_bw() + geom_vline(xintercept = 0, colour = "grey50", size = 0.5) + geom_hline(yintercept = 0, colour = "grey50", size = 0.5) + geom_ribbon( data = dplyr::filter(df, .data$x > 0), aes(ymax = .data$y), ymin = 0, fill = "grey50", alpha = 0.2) + geom_line() + annotate( geom = "text", label = paste0("p(IB(theta)>0,k==", wtp, ")"), parse = TRUE, x = df$x[which.max(df$y)], y = max(df$y), hjust = -0.5, vjust = 1, size = 3.5) + coord_cartesian(xlim = xlim) labs.title <- paste0("Incremental Benefit Distribution\n", he$interventions[he$ref]," vs ", he$interventions[he$comp[comparison]], "") ib + theme( text = element_text(size = 11), panel.grid = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank()) + labs(title = labs.title, x = parse(text = "IB(theta)"), y = "Density") + theme(plot.title = element_text( lineheight = 1.05, face = "bold", size = 14.3, hjust = 0.5)) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/ib_plot_ggplot.R
#' @rdname info.rank #' @title Information-Rank Plot for bcea Class #' #' @importFrom rlang .data #' @importFrom dplyr slice desc #' @importFrom graphics barplot #' @import ggplot2 #' #' @export #' info.rank.bcea <- function(he, inp, wtp = NULL, howManyPars = NA, graph = c("base", "ggplot2", "plotly"), rel = TRUE, ...) { graph <- match.arg(graph) extra_args <- list(...) graph_params <- inforank_params(he, inp, wtp, rel, howManyPars, extra_args) if (is_baseplot(graph)) { info_rank_base(he, graph_params) } else if (is_ggplot(graph)) { info_rank_ggplot(he, graph_params) } else { info_rank_plotly(graph_params) } } #' @title Information-Rank Plot #' #' @description Produces a plot similar to a tornado plot, but based on the analysis of the #' EVPPI. For each parameter and value of the willingness-to-pay threshold, a #' barchart is plotted to describe the ratio of EVPPI (specific to that #' parameter) to EVPI. This represents the relative `importance' of each #' parameter in terms of the expected value of information. #' #' @template args-he #' @param inp Named list from running `createInputs()` containing: #' \itemize{ #' \item `parameter` = A vector of parameters for which the individual EVPPI #' should be calculated. This can be given as a string (or vector of strings) #' of names or a numeric vector, corresponding to the column numbers of #' important parameters. #' \item `mat` = A matrix containing the simulations for all the parameters #' monitored by the call to JAGS or BUGS. The matrix should have column names #' matching the names of the parameters and the values in the vector parameter #' should match at least one of those values. #' } #' @param wtp A value of the wtp for which the analysis should be performed. If #' not specified then the break-even point for the current model will be used. #' @param howManyPars Optional maximum number of parameters to be included in the bar plot. #' Includes all parameters by default. #' @param graph A string used to select the graphical engine to use for plotting. #' Should (partial-)match one of the two options "base" or "plotly". Default value is "base" #' @param rel Logical argument that specifies whether the ratio of #' EVPPI to EVPI (`rel = TRUE`, default) or the absolute value of the EVPPI #' should be used for the analysis. #' @param ... Additional options. These include graphical parameters that the #' user can specify: #' \itemize{ #' \item `xlim` = limits of the x-axis; ca = font size for the axis #' label (default = 0.7 of full size). #' \item `cn` = font size for the parameter names #' vector (default = 0.7 of full size) - base graphics only. #' \item `mai` = margins of the graph (default = c(1.36, 1.5, 1,1)) - base graphics only. #' } #' @return With base graphics: A data.frame containing the ranking of the parameters #' with the value of the selected summary, for the chosen wtp; with plotly: a plotly object, #' incorporating in the $rank element the data.frame as above. #' The function produces a 'Info-rank' plot. This is an extension of standard 'Tornado #' plots' and presents a ranking of the model parameters in terms of their #' impact on the expected value of information. For each parameter, the #' specific individual EVPPI is computed and used to measure the impact of #' uncertainty in that parameter over the decision-making process, in terms of #' how large the expected value of gaining more information is. #' #' @author Anna Heath, Gianluca Baio, Andrea Berardi #' @seealso [bcea()], #' [evppi()] #' @importFrom Rdpack reprompt #' #' @references #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords dplot models #' #' @export #' #' @examples #' \dontrun{ #' # Load the post-processed results of the MCMC simulation model #' # original JAGS output is can be downloaded from here #' # https://gianluca.statistica.it/book/bcea/code/vaccine.RData #' #' data("Vaccine") #' m <- bcea(eff, cost) #' inp <- createInputs(vaccine_mat) #' info.rank(m, inp) #' #' info.rank(m, inp, graph = "base") #' info.rank(m, inp, graph = "plotly") #' info.rank(m, inp, graph = "ggplot2") #' } #' info.rank <- function(he, ...) { UseMethod('info.rank', he) } # prevent BCEA::evppi from throwing messages quiet <- function(x) { sink(tempfile()) on.exit(sink()) invisible(force(x)) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/info.rank.R
#' Info Rank Plot By Graph Device #' #' Choice of base R, \pkg{ggplot2} and \pkg{plotly}. #' @name info_rank_graph #' NULL #' Info rank plot base R version #' @rdname info_rank_graph #' #' @template args-he #' @param params Graph parameters #' info_rank_base <- function(he, params) { res <- params$res default_params <- list(ca = 0.7, # cex.axis cn = 0.7, # cex.names mai = c(1.36, 1.5, 1, 1), space = 0.5) plot_params <- modifyList(default_params, params) par_default <- par(no.readonly = TRUE) on.exit(par(par_default)) col <- rep(c("blue", "red"), length(plot_params$chk2)) par(mai = plot_params$mai) do.call(barplot, list(height = res$info, horiz = TRUE, names.arg = res$parameter, cex.names = plot_params$cn, las = 1, col = col, cex.axis = plot_params$ca, xlab = plot_params$xlab, space = plot_params$space, main = plot_params$tit, xlim = plot_params$xlim)) decrease_order <- order(res$info, decreasing = TRUE) invisible( list( rank = data.frame( parameter = res$parameter[decrease_order], info = res$info[decrease_order]))) } #' Info rank plot ggplot2 version #' @rdname info_rank_graph #' #' @template args-he #' @param params Graph parameters #' @importFrom stats reorder #' info_rank_ggplot <- function(he, params) { ggplot(data = params$res, aes(x = reorder(.data$parameter, .data$info), y = .data$info)) + geom_bar(stat = "identity") + coord_flip() + theme_default() + scale_fill_manual(rep(c("red","blue"), nrow(params$res))) + ylab(params$xlab) + xlab("") + ggtitle(params$tit) } #' Info rank plot plotly version #' @rdname info_rank_graph #' #' @param params Graph Parameters including data #' @export #' @importFrom cli cli_alert_warning #' info_rank_plotly <- function(params) { if (exists("ca", where = params)) { cli::cli_alert_warning( "Argument {.var ca} was specified in {.fn info.rank.plotly} but is not an accepted argument. Parameter will be ignored.") } if (exists("cn", where = params)) { cli::cli_alert_warning( "Argument {.var cn} was specified in {.fn info.rank.plotly} but is not an accepted argument. Parameter will be ignored.") } res <- params$res default_params <- list(mai = c(1.36, 1.5, 1, 1), space = 0.5, ca = NULL, cn = NULL) plot_params <- modifyList(params, default_params) p <- plotly::plot_ly( data = res, y = ~reorder(.data$parameter, .data$info), x = ~.data$info, orientation = "h", type = "bar", marker = list(color = "royalblue")) p <- plotly::layout( p, xaxis = list(hoverformat = ".2f", title = plot_params$xlab, range = plot_params$xlim), yaxis = list(hoverformat = ".2f", title = ""), margin = plot_params$mai, bargap = plot_params$space, title = plot_params$tit) decrease_order <- order(res$info, decreasing = TRUE) p$rank <- data.frame(parameter = res$parameter[decrease_order], info = res$info[decrease_order]) return(p) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/info_rank_graph.R
#' Prepare Info Rank plot parameters #' #' @template args-he #' @param inp Inputs #' @param wtp Willingness to pay #' @param rel Relative size #' @param howManyPars How mnay parameters to use? #' @param extra_args Additional arguments #' #' @importFrom purrr map_int #' @importFrom dplyr slice arrange desc #' @keywords internal #' inforank_params <- function(he, inp, wtp = NULL, rel, howManyPars, extra_args) { parameter <- inp$parameters input <- inp$mat ##TODO: what to do for multiple ICER? if (is.null(wtp)) wtp <- he$k[min(which(he$k >= he$ICER[1]))] if (!wtp %in% he$k) stop("wtp must be from values computed in call to bcea().", call. = FALSE) if (is.character(parameter[1])) { parameters <- array() for (i in seq_along(parameter)) { parameters[i] <- which(colnames(input) == parameter[i]) } } else { parameters <- parameter } parameter <- colnames(input)[parameters] # exclude parameters with weird behaviour (ie all 0s) w <- map_int(parameter, function(x) which(colnames(input) == x)) if (length(w) == 1) return() input <- input[, w] ##TODO: what does this do? where is this used? # chk1 <- which(apply(input, 2, "var") > 0) # only takes those with var > 0 # check those with < 5 possible values (would break GAM) tmp <- lapply(seq_len(dim(input)[2]), function(x) table(input[, x])) chk2 <- which(unlist(lapply(tmp, function(x) length(x) >= 5)) == TRUE) names(chk2) <- colnames(input[, chk2]) N <- he$n_sim ##TODO: what does select do? if (any(!is.na(N)) && length(N) > 1) { # select <- N } else { N <- min(he$n_sim,N, na.rm = TRUE) # select <- # if (N == he$n_sim) { # 1:he$n_sim # } else { # sample(1:he$n_sim, size = N, replace = FALSE)} } m <- he m$k <- wtp x <- list() for (i in seq_along(chk2)) { x[[i]] <- quiet( evppi(he = m, param_idx = chk2[i], input = input, N = N)) } scores <- if (rel) { unlist(lapply(x, function(x) x$evppi/x$evi[which(he$k == wtp)])) } else { unlist(lapply(x, function(x) x$evppi)) } xlab <- ifelse(rel, "Proportion of total EVPI", "Absolute value of the EVPPI") tit <- paste0("Info-rank plot for willingness to pay = ", wtp) xlim <- c(0, range(scores)[2]) res <- data.frame( parameter = names(chk2), info = scores) res <- dplyr::arrange(res, dplyr::desc(.data$info)) change_num_pars <- !is.null(howManyPars) && is.numeric(howManyPars) && howManyPars > 0 if (change_num_pars) { howManyPars <- min(howManyPars, nrow(res)) res <- dplyr::slice(res, 1:howManyPars) } res <- res[order(res$info), ] modifyList( list(res = res, scores = scores, chk2 = chk2, tit = tit, xlim = xlim, xlab = xlab, howManyPars = howManyPars), extra_args) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/inforank_params.R
#' Prepare K-star vertical lines #' #' @template args-he #' @param plot_params Plots parameters #' @keywords internal #' kstar_vlines <- function(he, plot_params) { if (length(he$kstar) > 0) { abline(v = he$kstar, col = "dark grey", lty = "dotted") text(x = he$kstar, y = min(plot_params$ylim), paste("k* = ", he$kstar , sep = "")) } }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/kstar_vlines.R
# Package: ldr # Type: Package # Title: Methods for likelihood-based dimension reduction in regression # Version: 1.3.3 # Date: 2014-06-06 # Author: Kofi Placid Adragni, Andrew Raim # Maintainer: Kofi Placid Adragni <[email protected]> # Description: Functions, methods, and data sets for fitting likelihood-based dimension reduction in regression, # using principal fitted components (pfc), likelihood acquired directions (lad), covariance reducing models (core). # URL: https://www.jstatsoft.org/v61/i03/ # License: GPL (>= 2) # Packaged: 2021-10-08 16:32:42 UTC; Nathan # Repository: https://github.com/cran/ldr # Date/Publication: 2014-10-29 16:36:14 # # Likelihood Acquired Directions # # Method to estimate the central subspace, using inverse conditional mean and conditional variance functions. # #' @importFrom stats cov lm #' lad <- function(X, y, numdir=NULL, nslices=NULL, numdir.test=FALSE,...) { mf <- match.call() op <- dim(X); p <- op[2]; n <- op[1]; yy <- y; yfactor <- FALSE verbose <- mf$verbose; if (is.null(verbose)) verbose <- FALSE if (is.factor(y)) {yy <- as.vector(as.integer(factor(y, levels=unique(y)))) yfactor <- TRUE} if (n != length(yy)) stop("X and y do not have the same number of observations") if (p > n) stop("This method requires n larger than p") vnames <- dimnames(X)[[2]] if (is.null(vnames)) vnames <- paste("X", 1:p, sep="") X <- as.matrix(X) Sigmatilde <- cov(X) if (is.null(nslices)) if (verbose) message("The response is treated as categorical.") if (is.null(nslices)) { groups <- unique(sort(yy)) use.nslices <- length(groups) if (identical(use.nslices, 1)) stop("The response has a single level.") numdir <- min(p, use.nslices-1) N_y <-vector(length=use.nslices) Deltatilde_y <- vector(length=use.nslices, "list") for (i in 1:use.nslices) { N_y[i] <- length(yy[yy==groups[i]]) X_y <- X[which(yy == groups[i]),] Deltatilde_y[[i]] <- cov(X_y) } } if (!is.null(nslices)) { if (identical(nslices, 1)) stop("You need at least two slices.") use.nslices <- nslices if (is.null(numdir)) numdir <- min(p, nslices-1) ysort <- ldr.slices(yy, nslices) N_y <-vector(length=nslices) Deltatilde_y <- vector(length=nslices, "list") for (i in 1:nslices) { N_y[i] <- sum(ysort$slice.indicator==i) X_y <- X[which(ysort$slice.indicator == i),] Deltatilde_y[[i]] <- cov(X_y) } } Sigmas <- list(Sigmatilde=Sigmatilde, Deltatilde_y=Deltatilde_y, N_y=N_y) Deltatilde <- 0 for (i in 1:use.nslices) Deltatilde <- Deltatilde + N_y[i] * Deltatilde_y[[i]] if (identical(numdir.test, FALSE)) { fit <- onelad(numdir, Deltatilde, p, Sigmatilde, Deltatilde_y, N_y, use.nslices, mf, X, yy, Sigmas, vnames, ...) R <- X%*%fit$Gammahat ans <- list(R=R, Gammahat=fit$Gammahat, Deltahat=fit$Deltahat, Deltahat_y=fit$Deltahat_y, loglik=fit$loglik, aic=fit$aic, bic=fit$bic, numpar=fit$numpar, numdir=numdir, yfactor=yfactor, y=y, model="lad", call=match.call(expand.dots=TRUE),numdir.test=numdir.test) class(ans) <- "lad" return(invisible(ans)) } aic <- bic <- numpar <- loglik <- vector(length=numdir+1) Deltahat <- Deltahat_y <- Gammahat <-vector("list") for (i in 0:numdir) { fit <- onelad(i, Deltatilde, p, Sigmatilde, Deltatilde_y, N_y, use.nslices, mf, X, yy, Sigmas, vnames, ...) Gammahat[[i+1]] <-fit$Gammahat Deltahat[[i+1]] <- fit$Deltahat Deltahat_y[[i+1]] <- fit$Deltahat_y loglik[i+1] <- fit$loglik numpar[i+1] <- fit$numpar aic[i+1] <- fit$aic bic[i+1] <- fit$bic } R <- X%*%Gammahat[[numdir+1]] ans <- list(R=R, Gammahat=Gammahat, Deltahat=Deltahat, Deltahat_y=Deltahat_y, loglik=loglik, aic=aic, bic=bic, numpar=numpar, numdir=numdir, model="lad", call=match.call(expand.dots=TRUE), yfactor=yfactor, y=y, numdir.test=numdir.test) class(ans)<- "lad" return(invisible(ans)) } #' @importFrom stats cov #' InitialMatrix <- function(X, y, nslices) { op <- dim(X) n <- op[1] p <- op[2] if (is.null(nslices)) { yunique <- sort(unique(y)) ygroups <- y nslices <- length(unique(y)) } else { Slicing <- ldr.slices(y, nslices=nslices) yunique <- sort(unique(Slicing$slice.indicator)) ygroups <- Slicing$slice.indicator } SigmaX <- cov(X) X0 <- as.matrix(X - kronecker(cbind(rep(1,n)), rbind(apply(X,2,mean)))) svdS<-svd(SigmaX) InvSqrtX <- svdS$u %*% diag(c(svdS$d)^(-0.5)) %*% t(svdS$v) Z <- X0%*%InvSqrtX pv <- vector(length=nslices) for (i in 1:nslices) pv[i] <- sum(ygroups==yunique[i])/length(y) cez <- matrix(0,p,nslices) cezz <- array(0,dim=c(p,p,nslices)) for (i in 1:nslices){ for (j in 1:n){ cez[,i] <- cez[,i] + Z[j,]*(ygroups[j]==i) cezz[,,i] <- cezz[,,i] + Z[j,]%*%t(Z[j,])*(ygroups[j]==i) } cez[,i] <- cez[,i]/n/pv[i] cezz[,,i] <- cezz[,,i]/n/pv[i] } mat1 <- mat2 <- mat4 <- mat5 <- matrix(0,p,p) mat3 <- 0 for (i in 1:nslices){ mat1 <- mat1 + cezz[,,i]%*%cezz[,,i]*pv[i] mat2 <- mat2 + cez[,i]%*%t(cez[,i])*pv[i] mat3 <- mat3 + sum(cez[,i]^2)*pv[i] mat4 <- mat4 + cezz[,,i]%*%cez[,i]%*%t(cez[,i])*pv[i] mat5 <- mat5 + sum(cez[,i]^2)*cez[,i]%*%t(cez[,i])*pv[i] } dr <- 2*mat1 + 2*mat2%*%mat2 + 2*mat3*mat2 - 2*diag(p) vector.dr <- eigen(dr)$vectors dr.direction <- InvSqrtX %*%vector.dr Wdr <- orthonorm(dr.direction) # using SIR sir <- mat2 vector.sir <- eigen(sir)$vectors sir.direction <- InvSqrtX %*%vector.sir Wsir <- orthonorm(sir.direction) # Using SAVE save <- mat1 - diag(p) - mat4 - t(mat4) + 2*sir + mat5 vector.save <- eigen(save)$vectors save.direction <- InvSqrtX %*%vector.save Wsave <- orthonorm(save.direction) return(list(Wsir=Wsir, Wsave=Wsave, Wdr=Wdr)) } #' onelad <-function(d, Deltatilde, p, Sigmatilde, Deltatilde_y, N_y, use.nslices, mf, X, yy, Sigmas, vnames, ...) { if (d == 0) { Gammahat <- NULL Deltahat <- Deltatilde terme0 <- -(n*p)*(1+log(2*pi))/2 terme1 <- -n*log( det(Sigmatilde) )/2 loglik <- terme0 + terme1 Deltahat_y <- Deltatilde_y numpar <- p + p*(p+1)/2 AIC <- -2*loglik + 2 * numpar BIC <- -2*loglik + log(n) * numpar } else if (d==p) { Gammahat <- diag(p) Deltahat <- Deltatilde terme0 <- -(n*p)*(1+log(2*pi))/2 terme3 <- 0 for (i in seq_along(N_y)) { terme3 <- terme3 - N_y[i] * log( det(Deltatilde_y[[i]]) )/2 } loglik <- terme0 + terme3 Deltahat_y <- Deltatilde_y numpar <- p+(use.nslices-1)*d + p*(p+1)/2 + (use.nslices-1)*d*(d+1)/2 AIC <- -2*loglik + 2 * numpar BIC <- -2*loglik + log(n) * numpar } else { objfun <- function(W) { Q <- W$Qt d <- W$dim[1] p <- W$dim[2] Sigmas <- W$Sigmas n <- sum(Sigmas$N_y) U <- matrix(Q[,1:d], ncol=d) V <- matrix(Q[,(d+1):p], ncol=(p-d)) # Objective function terme0 <- -(n*p)*(1+log(2*pi))/2 terme1 <- -n*log(det(Sigmas$Sigmatilde))/2 term <- det(t(U)%*%Sigmas$Sigmatilde%*%U) if (is.null(term)|is.na(term)|(term <= 0)) return(NA) else terme2 <- n*log(term)/2 terme3<-0 for (i in seq_along(Sigmas$N_y)) { term <- det(t(U)%*%Sigmas$Deltatilde_y[[i]]%*%U) if (is.null(term)|is.na(term)|(term <=0)) {break return(NA)} terme3 <- terme3 - Sigmas$N_y[i] * log(term)/2 } value <- terme0 + terme1 + terme2 + terme3 #Gradient terme0 <- solve(t(U)%*%Sigmas$Sigmatilde%*%U) terme1 <- sum(Sigmas$N_y) * t(V)%*%Sigmas$Sigmatilde%*%U%*%terme0 terme2 <- 0 for (i in seq_along(Sigmas$N_y)) { temp0 <- solve(t(U)%*%Sigmas$Deltatilde_y[[i]]%*%U) temp <-Sigmas$N_y[i]*t(V)%*%Sigmas$Deltatilde_y[[i]]%*%U%*%temp0 terme2 <- terme2 - temp } gradient <- t(terme1 + terme2) return(list(value=value, gradient=gradient)) } objfun <- assign("objfun", objfun, envir=.BaseNamespaceEnv) if (is.null(mf$sim_anneal)) { Wlist <- InitialMatrix(X=X, y=yy, use.nslices) values <- c(objfun(W=list(Qt=Wlist$Wsir, dim=c(d,p), Sigmas=Sigmas))$value, objfun(W=list(Qt=Wlist$Wsave, dim=c(d,p), Sigmas=Sigmas))$value, objfun(W=list(Qt=Wlist$Wdr, dim=c(d,p), Sigmas=Sigmas))$value) W <- list(Qt=Wlist[[which(values == max(values))[1]]], dim=c(d,p), Sigmas=Sigmas) grassmann <- GrassmannOptim(objfun, W, ...) } if (!is.null(mf$sim_anneal)) { W <- list(dim=c(d,p), Sigmas=Sigmas) grassmann <- GrassmannOptim(objfun, W,...) } Gammahat <- matrix(grassmann$Qt[,1:d], ncol=d) dimnames(Gammahat) <- list(vnames, paste("Dir", 1:d, sep="")) invDeltahat <- solve(Sigmatilde) + Gammahat%*%solve(t(Gammahat)%*%Deltatilde%*%Gammahat)%*%t(Gammahat) - Gammahat%*%solve(t(Gammahat)%*%Sigmatilde%*%Gammahat)%*%t(Gammahat) Deltahat <- solve(invDeltahat); Pj <- projection(Gammahat, Deltahat) Deltahat_y <- vector("list", use.nslices) for (i in seq_len(use.nslices)) { Deltahat_y[[i]] <- Deltahat + t(Pj) %*% (Deltatilde_y[[i]] - Deltahat)%*%Pj } terme0 <- -(n*p)*(1+log(2*pi))/2 terme1 <- -n*log( det(Sigmatilde) )/2 terme2 <- n*log(det(t(Gammahat)%*%Sigmatilde%*%Gammahat))/2 terme3<-0 for (i in seq_along(N_y)) { terme3 <- terme3 - N_y[i] * log( det(t(Gammahat)%*%Deltatilde_y[[i]]%*%Gammahat) )/2 } loglik <- terme0 + terme1 + terme2 + terme3 numpar <- p+(use.nslices-1)*d+p*(p+1)/2+d*(p-d)+(use.nslices-1)*d*(d+1)/2 AIC <- -2*loglik + 2 * numpar BIC <- -2*loglik + log(n) * numpar } return(list(Gammahat=Gammahat, Deltahat=Deltahat, Deltahat_y=Deltahat_y, loglik=loglik, numpar=numpar, aic=AIC, bic=BIC)) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/lad.R
# Package: ldr # Type: Package # Title: Methods for likelihood-based dimension reduction in regression # Version: 1.3.3 # Date: 2014-06-06 # Author: Kofi Placid Adragni, Andrew Raim # Maintainer: Kofi Placid Adragni <[email protected]> # Description: Functions, methods, and data sets for fitting likelihood-based dimension reduction in regression, # using principal fitted components (pfc), likelihood acquired directions (lad), covariance reducing models (core). # URL: https://www.jstatsoft.org/v61/i03/ # License: GPL (>= 2) # Packaged: 2021-10-08 16:32:42 UTC; Nathan # Repository: https://github.com/cran/ldr # Date/Publication: 2014-10-29 16:36:14 # # Likelihood-based Dimension Reduction # # Main function of the package. It creates objects of one of classes core, lad, # or pfc to estimate a sufficient dimension reduction subspace using covariance reducing models (CORE), # likelihood acquired directions (LAD), or principal fitted components (PFC). # ldr <- function(X, y=NULL, fy=NULL, Sigmas=NULL, ns=NULL, numdir=NULL, nslices=NULL, model=c("core", "lad", "pfc"), numdir.test=FALSE, ...) { if (model=="pfc") { if (is.null(fy)){stop("fy is not provided"); return()} return(invisible(pfc(X=X, y=y, fy=fy, numdir=numdir, numdir.test=numdir.test, ...))) } if (model=="lad") { if (is.null(y)){stop("The response is needed"); return()} return(invisible(lad(X=X, y=y, numdir=numdir, nslices=nslices, numdir.test=numdir.test,...))) } if (model=="core") { if (!is.null(Sigmas) && !is.null(ns)) return(invisible(core(Sigmas=Sigmas, ns=ns, numdir=numdir, numdir.test=numdir.test,...))) return(invisible(core(X=X, y=y, numdir=numdir, numdir.test=numdir.test,...))) } }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/ldr.R
# Package: ldr # Type: Package # Title: Methods for likelihood-based dimension reduction in regression # Version: 1.3.3 # Date: 2014-06-06 # Author: Kofi Placid Adragni, Andrew Raim # Maintainer: Kofi Placid Adragni <[email protected]> # Description: Functions, methods, and data sets for fitting likelihood-based dimension reduction in regression, # using principal fitted components (pfc), likelihood acquired directions (lad), covariance reducing models (core). # URL: https://www.jstatsoft.org/v61/i03/ # License: GPL (>= 2) # Packaged: 2021-10-08 16:32:42 UTC; Nathan # Repository: https://github.com/cran/ldr # Date/Publication: 2014-10-29 16:36:14 # # Divides a vector of length n into slices of approximately equal size. # It is used to construct the piecewise bases, and internally used in lad functions. # ldr.slices <- function(y, nslices=3) { endpoints <- function(n, nslices) { # This function is intended to determine the end-points of the slices. increment <- floor(n/nslices) if (nslices ==1) return(n) if (nslices > 1) { ends<- seq(1:nslices)*increment rest <- n%%nslices if (rest==0) return(ends) if (rest>0) { for (i in 1:rest) ends[i]<-ends[i]+i for (i in (rest+1):nslices) ends[i]<- ends[i]+rest return(ends) } } } n <- length(y) indicators <- vector(length=n) sorty <- sort(y) bins.y <- vector("list", nslices) ends <- endpoints(n, nslices) if (nslices==1) { bins.y[[1]] <- sorty[1:ends[1]] indicators[1:ends[1]]<-1 return(list(bins=bins.y, nslices=nslices, slice.size=n, slice.indicator=indicators[rank(y)])) } else if (nslices==2) { bins.y[[1]] <- sorty[1:ends[1]] bins.y[[2]] <- sorty[(ends[1]+1):ends[2]] indicators[1:ends[1]]<-1 indicators[(ends[1]+1):ends[2]]<-2 return(list(bins=bins.y, nslices=nslices, slice.size=diff(c(0,ends)), slice.indicator=indicators[rank(y)])) } else { bins.y[[1]] <- sorty[1:(ends[1]-1)] indicators[1:(ends[1]-1)]<-1 for (i in 2:(nslices-1)) { bins.y[[i]] <- sorty[ends[i-1]:(ends[i]-1)] indicators[ends[i-1]:(ends[i]-1)] <- i } bins.y[[nslices]] <- sorty[ends[nslices-1]:(ends[nslices])] indicators[ends[nslices-1]:(ends[nslices])] <- nslices return(list(bins=bins.y, nslices=nslices, slice.size=diff(c(0,ends)), slice.indicator=indicators[rank(y)])) } }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/ldr.slices.R
#' Create Labels for Plot #' #' @template args-he #' @param ... Additional arguments #' @export #' @keywords internal #' line_labels <- function(he, ...) UseMethod("line_labels", he) #' Swapped labels so that reference is second #' @rdname line_labels #' @export #' line_labels.default <- function(he, ref_first = TRUE, ...) { if (he$n_comparisons == 1) return("") if (ref_first) { paste(he$interventions[he$ref], "vs", he$interventions[he$comp]) } else { paste(he$interventions[he$comp], "vs", he$interventions[he$ref]) } } #' @rdname line_labels #' @export #' line_labels.pairwise <- function(he, ...) { he$interventions[c(he$comp, he$ref)] }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/line_labels.R
#' @importFrom utils methods #' list_plot_methods <- function() { m <- methods(class = "bcea") m[grep(pattern = "plot", m)] }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/list_methods.R
#' Make Report #' #' Constructs the automated report from the output of the BCEA. #' #' @template args-he #' @param evppi An object obtained as output to a call to `evppi` #' (default is NULL, so not essential to producing the report). #' @param ext A string of text to indicate the extension of the #' resulting output file. Possible options are `"pdf"`, `"docx"`. #' This requires the use of pandoc, knitr and rmarkdown. #' @param echo A string (default to `FALSE`) to instruct whether #' the report should also include the `BCEA` commands used to #' produce the analyses. If the optional argument `echo` is set #' to `TRUE` (default = `FALSE`), then the commands are also #' printed. #' @param ... Additional parameters. For example, the user can specify the #' value of the willingness to pay `wtp`, which is used in some of #' the resulting analyses (default at the break even point). #' Another additional parameter that the user can specify is the name #' of the file to which the report should be written. This can be done #' by simply passing the optional argument `filename="NAME"`. #' The user can also specify an object including the PSA simulations #' for all the relevant model parameters. If this is passed to the #' function (in the object `psa_sims`), #' then `make.report` will automatically construct an "Info-rank #' plot", which is a probabilistic form of tornado plot, based on the #' Expected Value of Partial Information. The user can also specify #' the optional argument `show.tab` (default=FALSE); if set to #' `TRUE`, then a table with the values of the Info-rank is also #' shown. #' #' @author Gianluca Baio #' @seealso [bcea()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @export #' #' @examples #' #' \dontrun{ #' data(Vaccine, package = "BCEA") #' m <- bcea(eff, cost, ref = 2) #' make.report(m) #' } #' make.report <- function(he, evppi = NULL, ext = "pdf", echo = FALSE, ...) { # check if knitr installed (and if not, asks for it) if(!isTRUE(requireNamespace("knitr", quietly = TRUE))) { stop("You need to install the R package 'knitr'. Please run in your R terminal:\n install.packages('knitr')", call. = FALSE) } knitr::opts_knit$set(progress = FALSE, verbose = FALSE) # check if rmarkdown installed (and if not, asks for it) if(!isTRUE(requireNamespace("rmarkdown", quietly = TRUE))) { stop("You need to install the R package 'rmarkdown'. Please run in your R terminal:\n install.packages('rmarkdown')", call. = FALSE) } extra_args <- list(...) wtp <- if (exists("wtp", extra_args)) { extra_args$wtp } else { he$k[min(which(he$k >= he$ICER))] } filename <- if (exists("filename", extra_args)) { extra_args$filename } else { paste0("Report.", ext)} psa_params <- if (exists("psa_sims", extra_args)) { extra_args$psa_sims } else { NULL} show.tab <- if (exists("show.tab", extra_args)) { TRUE } else { FALSE} rmd_params <- list(wtp = wtp, filename = filename, psa_params = psa_params, ext = ext, show.tab = show.tab) # remove all warnings withr::with_options(list(warn = -1), { # get current directory, move to relevant path, go back to current directory file <- file.path(tempdir(), filename) bcea_file_location <- normalizePath( file.path(system.file("rmarkdown","report", package = "BCEA"), "report.Rmd")) rmd_format <- switch(ext, pdf = rmarkdown::pdf_document(), docx = rmarkdown::word_document()) out <- quiet( rmarkdown::render(bcea_file_location, output_format = rmd_format, params = rmd_params)) file.copy(from = out, to = file, overwrite = TRUE) cat(paste0("The report is saved in the file ", file, "\n")) }) } #' Allow disabling of the cat messages #' @param x Object to quietly return #' @keywords internal #' quiet <- function(x) { sink(tempfile()) on.exit(sink()) invisible(force(x)) } #' Automatically open pdf output using default pdf viewer #' #' @param file_name String file names for pdf #' @keywords internal #' openPDF <- function(file_name) { os <- .Platform$OS.type if (os == "windows") shell.exec(normalizePath(file_name)) else { pdf <- getOption("pdfviewer", default = '') if (nchar(pdf) == 0) stop("The 'pdfviewer' option is not set. Use options(pdfviewer = ...)") system2(pdf, args = c(file_name)) } }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/make.report.R
#' @keywords dplot internal #' evppi_legend_base <- function(evppi_obj, pos_legend, col = NULL) { legend_here <- where_legend(evppi_obj, pos_legend) text <- evppi_legend_text(evppi_obj) cols <- evppi_legend_cols(evppi_obj, col) list(x = legend_here, legend = text, cex = 0.7, bty = "n", lty = c(1, seq_along(evppi_obj$parameters)), lwd = c(2, rep(1, length(evppi_obj$parameters))), col = cols) } #' @keywords dplot internal #' ceac_legend_base <- function(he, pos_legend, plot_params) { pos_legend <- where_legend(he, pos_legend) text <- line_labels(he) list(x = pos_legend, legend = text, cex = 0.7, bty = "n", lty = plot_params$lty, col = plot_params$col, pch = plot_params$pch) } #' @keywords dplot internal #' ceplane_legend_base <- function(he, pos_legend, plot_params) { pos_legend <- where_legend(he, pos_legend) text <- line_labels(he, ref_first = plot_params$ref_first) list(x = pos_legend, legend = text, cex = 0.7, bty = "n", col = plot_params$points$col, pch = plot_params$points$pch) } #' @keywords internal #' where_legend <- function(he, pos_legend) { # cases with empty legend if (!inherits(he, "pairwise") && !inherits(he, "CEriskav") && ("n_comparisons" %in% names(he)) && he$n_comparisons == 1) return(NA) where_legend_always(he, pos_legend) } #' @keywords internal #' where_legend_always <- function(he, pos_legend) { if (is.numeric(pos_legend) && length(pos_legend) == 2) { ns <- ifelse(pos_legend[2] == 1, "top", "bottom") ew <- ifelse(pos_legend[1] == 1, "right", "left") return(paste0(ns, ew)) } if (is.logical(pos_legend)) { if (pos_legend) return("bottomleft") else return("bottomright") } if (grepl("(bottom|top)(left|right)", pos_legend)) return(pos_legend) message("Legend position not recognised.") return(NA) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/make_legend_base.R
#' @noRd #' @title make_legend_ggplot #' #' @description c(0, 0) corresponds to the “bottom left” #' c(1, 1) corresponds to the “top right” #' inside the plotting area #' #' @param dat data #' @param legend_pos Legend position #' #' @keywords internal #' make_legend_ggplot <- function(dat, legend_pos) { legend_just <- NULL # sets the corner that the legend_pos position refers to legend_dir <- NULL n_lines <- num_lines(dat) if (n_lines == 1) { legend_pos <- "none" } else if (any(is.na(legend_pos))) { legend_pos <- "none" } else if (is.logical(legend_pos)) { if (isTRUE(legend_pos)) { legend_pos <- "bottom" } else { legend_pos <- c(1, 0) legend_just <- legend_pos } } else if (is.character(legend_pos)) { pos_choices <- c("left", "right", "bottom", "top") legend_pos <- pos_choices[pmatch(legend_pos, pos_choices)] legend_just <- "center" } else if (is.numeric(legend_pos) && length(legend_pos) == 2) { legend_just <- legend_pos } else { # default legend_pos <- c(1, 0) legend_just <- legend_pos } list(legend.direction = legend_dir, legend.justification = legend_just, legend.position = legend_pos) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/make_legend_ggplot.R
#' Legend Positioning #' #' @param pos_legend Position of legend #' @return String #' #' @export #' @keywords internal #' make_legend_plotly <- function(pos_legend) { legend_params <- list(orientation = "v", xanchor = "center", x = 0.5, y = 0) if (is.character(pos_legend)) legend_params <- switch( pos_legend, "left" = list(orientation = "v", x = 0, y = 0.5), "bottomleft" = list(orientation = "v", x = 0, y = 0), "topleft" = list(orientation = "v", x = 0, y = 1), "right" = list(orientation = "v", x = 0, y = 0.5), "bottomright" = list(orientation = "v", x = 1, y = 0), "topright" = list(orientation = "v", x = 1, y = 1), "bottom" = list(orientation = "v", xanchor = "center", x = 0.5, y = 0), "top" = list(orientation = "h", xanchor = "center", x = 0.5, y = 100)) legend_params }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/make_legend_plotly.R
#' Plots the probability that each intervention is the most cost-effective #' #' This function is deprecated. Use [ceac.plot()] instead. #' Plots the probability that each of the n_int interventions being analysed is #' the most cost-effective. #' #' @param mce The output of the call to the function [multi.ce()]. #' @param pos Parameter to set the position of the legend. Can be given in form #' of a string `(bottom|top)(right|left)` for base graphics and #' `bottom|top|left|right` for ggplot2. It can be a two-elements vector, #' which specifies the relative position on the x and y axis respectively, or #' alternatively it can be in form of a logical variable, with `TRUE` #' indicating to use the first standard and `FALSE` to use the second one. #' Default value is `c(1,0.5)`, that is on the right inside the plot area. #' @param graph A string used to select the graphical engine to use for #' plotting. Should (partial-)match the two options `"base"` or #' `"ggplot2"`. Default value is `"base"`. #' @param ... Optional arguments. For example, it is possible to specify the #' colours to be used in the plot. This is done in a vector #' `color=c(...)`. The length of the vector colors needs to be the same as #' the number of comparators included in the analysis, otherwise `BCEA` #' will fall back to the default values (all black, or shades of grey) #' @return \item{mceplot}{ A ggplot object containing the plot. Returned only #' if `graph="ggplot2"`. } #' @author Gianluca Baio, Andrea Berardi #' @seealso [BCEA-deprecated()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords internal hplot #' @examples #' #' # See Baio G., Dawid A.P. (2011) for a detailed description of the #' # Bayesian model and economic problem #' #' \dontrun{ #' # Load the processed results of the MCMC simulation model #' data(Vaccine) #' # #' # Runs the health economic evaluation using BCEA #' m <- bcea(e=eff, c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e,c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000, # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0,Kmax) #' plot=FALSE # inhibits graphical output #' ) #' # #' mce <- multi.ce(m) # uses the results of the economic analysis #' # #' mce.plot(mce, # plots the probability of being most cost-effective #' graph="base") # using base graphics #' # #' if(require(ggplot2)){ #' mce.plot(mce, # the same plot #' graph="ggplot2") # using ggplot2 instead #' } #' } #' #' @export #' mce.plot <- function(mce, pos = c(1, 0.5), graph = c("base", "ggplot2"), ...) { # lifecycle::deprecate_warn("2.4.1", "mce.plot()", "ceac.plot()") .Deprecated(new = "ceac.plot", old = "mce.plot") alt.legend <- pos base.graphics <- ifelse(isTRUE(pmatch(graph,c("base","ggplot2"))==2),FALSE,TRUE) exArgs <- list(...) # Allows to specify colours for the plots # If the user doesn't specify anything, use defaults if(!exists("color",exArgs)) { color <- rep(1,(mce$n_comparators+1)); lwd <- 1 if (mce$n_comparators>7) { cl <- colors() color <- cl[floor(seq(262,340,length.out=mce$n_comparators))] # gray scale lwd <- 1.5 } } # If the user specify colours, then use but check they are the right number if(exists("color",exArgs)) { color <- exArgs$color lwd <- 1 if(mce$n_comparators>7) {lwd <- 1.5} if (length(color)!=(mce$n_comparators)) { message(paste0("You need to specify ",(mce$n_comparators)," colours. Falling back to default\n")) } } if(base.graphics) { if(is.numeric(alt.legend)&length(alt.legend)==2){ temp <- "" if(alt.legend[2]==0) temp <- paste0(temp,"bottom") else if(alt.legend[2]!=0.5) temp <- paste0(temp,"top") if(alt.legend[1]==1) temp <- paste0(temp,"right") else temp <- paste0(temp,"left") alt.legend <- temp if(length(grep("^((bottom|top)(left|right)|right)$",temp))==0) alt.legend <- FALSE } if(is.logical(alt.legend)){ if(!alt.legend) alt.legend <- "topright" else alt.legend <- "right" } # color <- rep(1,(mce$n_comparators+1)); lwd <- 1 # if (mce$n_comparators>7) { # cl <- colors() # color <- cl[floor(seq(262,340,length.out=mce$n_comparators))] # gray scale # lwd <- 1.5 # } plot(mce$k,mce$m.ce[,1],t="l",col=color[1],lwd=lwd,lty=1,xlab="Willingness to pay", ylab="Probability of most cost effectiveness",ylim=c(0,1), main="Cost-effectiveness acceptability curve \nfor multiple comparisons") for (i in 2:mce$n_comparators) { points(mce$k,mce$m.ce[,i],t="l",col=color[i],lwd=lwd,lty=i) } legend(alt.legend,mce$interventions,col=color,cex=.7,bty="n",lty=1:mce$n_comparators) } # base graphics else{ if(!isTRUE(requireNamespace("ggplot2",quietly=TRUE)&requireNamespace("grid",quietly=TRUE))) { message("Falling back to base graphics\n") mce.plot(mce,pos=pos,graph="base") return(invisible(NULL)) } if(isTRUE(requireNamespace("ggplot2",quietly=TRUE)&requireNamespace("grid",quietly=TRUE))) { # no visible bindings note ceplane <- k <- ce <- comp <- NA_real_ alt.legend <- pos lty <- rep(1:6,ceiling(mce$n_comparators/6))[1:mce$n_comparators] label <- paste0(mce$interventions) df <- cbind("k"=rep(mce$k,mce$n_comparators),"ce"=c(mce$m.ce)) df <- data.frame(df,"comp"=as.factor(sort(rep(1:mce$n_comparators,length(mce$k))))) names(df) <- c("k","ce","comp") mceplot <- ggplot2::ggplot(df, ggplot2::aes(x = k, y = ce)) + ggplot2::theme_bw() + ggplot2::geom_line(ggplot2::aes(linetype = comp)) + ggplot2::scale_linetype_manual("", labels = label, values = lty) + ggplot2::labs(title = "Cost-effectiveness acceptability curve\nfor multiple comparisons", x = "Willingness to pay", y = "Probability of most cost effectiveness") + ggplot2::theme( text = ggplot2::element_text(size = 11), legend.key.size = grid::unit(.66, "lines"), legend.spacing = grid::unit(-1.25, "line"), panel.grid = ggplot2::element_blank(), legend.key=ggplot2::element_blank()) jus <- NULL if(isTRUE(alt.legend)) { alt.legend <- "bottom" mceplot <- mceplot + ggplot2::theme(legend.direction="vertical") } else{ if(is.character(alt.legend)) { choices <- c("left", "right", "bottom", "top") alt.legend <- choices[pmatch(alt.legend,choices)] jus <- "center" if(is.na(alt.legend)) alt.legend <- FALSE } if(length(alt.legend)>1) jus <- alt.legend if(length(alt.legend)==1 & !is.character(alt.legend)) { alt.legend <- c(1,0.5) jus <- alt.legend } } mceplot <- mceplot + ggplot2::coord_cartesian(ylim = c(-0.05, 1.05)) + ggplot2::theme( legend.position = alt.legend, legend.justification = jus, legend.title = ggplot2::element_blank(), legend.background = ggplot2::element_blank(), legend.text.align = 0, plot.title = ggplot2::element_text( lineheight = 1.05, face = "bold", size = 14.3, hjust = 0.5 ) ) return(mceplot) } } }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/mce.plot.R
# `%||%` <- function(x, y) { if (is.null(x)) y else x }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/misc_helpers.R
#' @title Cost-Effectiveness Analysis When Multiple (Possibly Non-Cost-Effective) #' Interventions are Present on the Market #' #' @description Runs the cost-effectiveness analysis, but accounts for the fact that more #' than one intervention is present on the market. #' #' @aliases mixedAn mixedAn.default #' #' @template args-he #' @param value A vector of market shares associated with the interventions. #' Its size is the same as the number of possible comparators. #' By default, assumes uniform distribution for each intervention. #' #' @return Creates an object in the class `mixedAn`, a subclass of `bcea` #' which contains the results of the health economic evaluation in the mixed analysis case: #' \item{Ubar}{An array with the simulations of the ''known-distribution'' #' mixed utilities, for each value of the discrete grid approximation of the #' willingness to pay parameter} #' \item{OL.star}{An array with the simulations of the distribution of the #' Opportunity Loss for the mixed strategy, for each value of the discrete grid #' approximation of the willingness to pay parameter} #' \item{evi.star}{The Expected Value of Information for the mixed strategy, #' for each value of the discrete grid approximation of the willingness to pay #' parameter} #' \item{mkt.shares}{The vector of market shares associated with each available #' intervention} #' #' @author Gianluca Baio #' @seealso [bcea()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2009}{BCEA} #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @examples #' #' # See Baio G., Dawid A.P. (2011) for a detailed description of the #' # Bayesian model and economic problem #' #' # Load the processed results of the MCMC simulation model #' data(Vaccine) #' #' # Runs the health economic evaluation using BCEA #' m <- bcea(e=eff, c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e, c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000, # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0, Kmax) #' plot=FALSE) # inhibits graphical output #' #' mixedAn(m) <- NULL # uses the results of the mixed strategy #' # analysis (a "mixedAn" object) #' # the vector of market shares can be defined #' # externally. If NULL, then each of the T #' # interventions will have 1/T market share #' # produces the plots #' evi.plot(m) #' #' @export #' 'mixedAn<-' <- function(he, value) UseMethod('mixedAn<-', he)
/scratch/gouwar.j/cran-all/cranData/BCEA/R/mixedAn.R
#' @export #' 'mixedAn<-.bcea' <- function(he, value = NULL) { Ubar <- OL.star <- evi.star <- NULL value <- value %||% rep(1, he$n_comparators)/he$n_comparators Ubar <- compute_Ubar(he, value) OL.star <- he$Ustar - Ubar evi.star <- compute_EVI(OL.star) structure( modifyList( he, list( Ubar = Ubar, OL.star = OL.star, evi.star = evi.star, mkt.shares = value)), class = c("mixedAn", class(he))) } #' @export #' 'mixedAn<-.default' <- function(he, value) { stop("No method available", call. = FALSE) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/mixedAn.default.R
#' @name multi.ce #' @title Cost-effectiveness Analysis With Multiple Comparison #' #' @description Computes and plots the probability that each of the `n_int` interventions #' being analysed is the most cost-effective and the cost-effectiveness #' acceptability frontier. #' #' @template args-he #' #' @return Original `bcea` object (list) of class "pairwise" with additional: #' \item{p_best_interv}{A matrix including the probability that each #' intervention is the most cost-effective for all values of the willingness to #' pay parameter} #' \item{ceaf}{A vector containing the cost-effectiveness acceptability frontier} #' #' @author Gianluca Baio #' @seealso [bcea()], #' [ceaf.plot()] #' @keywords hplot dplot #' #' @examples #' # See Baio G., Dawid A.P. (2011) for a detailed description of the #' # Bayesian model and economic problem #' #' # Load the processed results of the MCMC simulation model #' data(Vaccine) #' #' # Runs the health economic evaluation using BCEA #' #' m <- bcea(e=eff, c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e,c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000, # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0,Kmax) #' plot=FALSE # inhibits graphical output #' ) #' #' mce <- multi.ce(m) # uses the results of the economic analysis #' #' ceac.plot(mce) #' ceaf.plot(mce) #' #' @export #' multi.ce.bcea <- function(he) { p_best_interv <- compute_p_best_interv(he) ceaf <- compute_ceaf(p_best_interv) res <- c(he, list(p_best_interv = p_best_interv, ceaf = ceaf)) structure(res, class = c("pairwise", class(he))) } #' @export #' multi.ce <- function(he) { UseMethod('multi.ce', he) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/multi.ce.R
#' Plot Multiple bcea Graphs #' #' Arrange plots in grid. Sourced from R graphics cookbook. #' #' @param plotlist List of ggplot objects #' @param cols Number of columns #' @param layout_config Matrix of plot configuration #' @return ggplot TableGrob object #' #' @importFrom gridExtra grid.arrange #' @keywords internal #' multiplot <- function(plotlist = NULL, cols = 1, layout_config = NULL) { n_plots <- length(plotlist) layout_config <- layout_config %||% matrix(seq(1, cols*ceiling(n_plots/cols)), ncol = cols, nrow = ceiling(n_plots/cols)) grid_params <- c(plotlist, list(layout_matrix = layout_config)) do.call("grid.arrange", grid_params) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/multiplot.R
#' Constructor for bcea #' #' @param df_ce Dataframe of all simulation eff and cost #' @param k Vector of willingness to pay values #' #' @import reshape2 dplyr #' @importFrom rlang int #' #' @return List object of class bcea. #' @seealso [bcea()] #' #' @export #' new_bcea <- function(df_ce, k) { # K <- length(k) ref <- unique(df_ce$ref) comp <- (1:max(df_ce$ints))[-ref] df_ce_comp <- df_ce %>% filter(.data$ints != ref) ICER <- compute_ICER(df_ce) ib <- compute_IB(df_ce, k) ceac <- compute_CEAC(ib) eib <- compute_EIB(ib) best <- best_interv_given_k(eib, ref, comp) kstar <- compute_kstar(k, best, ref) U <- compute_U(df_ce, k) Ustar <- compute_Ustar(U) vi <- compute_vi(Ustar, U) ol <- compute_ol(Ustar, U, best) evi <- compute_EVI(ol) interv_names <- levels(df_ce$interv_names) e_dat <- reshape2::dcast(sim ~ interv_names, value.var = "eff1", data = df_ce)[, -1] c_dat <- reshape2::dcast(sim ~ interv_names, value.var = "cost1", data = df_ce)[, -1] delta_e <- reshape2::dcast(sim ~ interv_names, value.var = "delta_e", data = df_ce_comp)[, -1, drop = FALSE] delta_c <- reshape2::dcast(sim ~ interv_names, value.var = "delta_c", data = df_ce_comp)[, -1, drop = FALSE] he <- list(n_sim = length(unique(df_ce$sim)), n_comparators = length(comp) + 1, n_comparisons = length(comp), delta_e = delta_e, delta_c = delta_c, ICER = ICER, Kmax = max(k), k = k, ceac = ceac, ib = ib, eib = eib, kstar = kstar, best = best, U = U, vi = vi, Ustar = Ustar, ol = ol, evi = evi, ref = ref, comp = comp, step = k[2] - k[1], interventions = interv_names, e = as.matrix(e_dat), c = as.matrix(c_dat)) structure(he, class = c("bcea", class(he))) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/new_bcea.R
# Number of lines # which depends on the type of plot #' @title Get number of lines #' @name num_lines #' @param dat Data #' @keywords internal #' num_lines <- function(dat) { UseMethod('num_lines', dat) } #' @rdname num_lines #' num_lines.pairwise <- function(dat) { dat$n_comparators } #' @rdname num_lines #' num_lines.bcea <- function(dat) { dat$n_comparisons } #' @rdname num_lines #' num_lines.evppi <- function(dat) { 2 } #' @rdname num_lines #' num_lines.default <- function(dat) { dat$n_comparisons }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/num_lines.R
# Package: ldr # Type: Package # Title: Methods for likelihood-based dimension reduction in regression # Version: 1.3.3 # Date: 2014-06-06 # Author: Kofi Placid Adragni, Andrew Raim # Maintainer: Kofi Placid Adragni <[email protected]> # Description: Functions, methods, and data sets for fitting likelihood-based dimension reduction in regression, # using principal fitted components (pfc), likelihood acquired directions (lad), covariance reducing models (core). # URL: https://www.jstatsoft.org/v61/i03/ # License: GPL (>= 2) # Packaged: 2021-10-08 16:32:42 UTC; Nathan # Repository: https://github.com/cran/ldr # Date/Publication: 2014-10-29 16:36:14 #' @importFrom cli cli_alert_warning # orthonorm <- function (u) { if (is.null(u)) return(NULL) if (!(is.matrix(u))) u <- as.matrix(u) dd <- dim(u) n <- dd[1] p <- dd[2] if (prod(abs(La.svd(u)$d) > 1e-08) == 0) stop("collinears vectors in orthonorm") if (n < p) { cli::cli_alert_warning( "There are too many vectors to orthonormalize in orthonorm.") u <- as.matrix(u[, 1:p]) n <- p } v <- u if (p > 1) { for (i in 2:p) { coef.proj <- c(crossprod(u[, i], v[, 1:(i - 1)]))/diag(crossprod(v[, 1:(i - 1)])) v[, i] <- u[, i] - matrix(v[, 1:(i - 1)], nrow = n) %*% matrix(coef.proj, nrow = i - 1) } } coef.proj <- 1/sqrt(diag(crossprod(v))) return(t(t(v) * coef.proj)) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/orthonorm.R
# Package: ldr # Type: Package # Title: Methods for likelihood-based dimension reduction in regression # Version: 1.3.3 # Date: 2014-06-06 # Author: Kofi Placid Adragni, Andrew Raim # Maintainer: Kofi Placid Adragni <[email protected]> # Description: Functions, methods, and data sets for fitting likelihood-based dimension reduction in regression, # using principal fitted components (pfc), likelihood acquired directions (lad), covariance reducing models (core). # URL: https://www.jstatsoft.org/v61/i03/ # License: GPL (>= 2) # Packaged: 2021-10-08 16:32:42 UTC; Nathan # Repository: https://github.com/cran/ldr # Date/Publication: 2014-10-29 16:36:14 # # Principal fitted components # # Principal fitted components model for sufficient dimension reduction. # This function estimates all parameters in the model. # #' @importFrom stats cov #' pfc <- function(X, y, fy = NULL, numdir = NULL, structure = c("iso", "aniso", "unstr", "unstr2"), eps_aniso = 1e-3, numdir.test = FALSE, ...) { "%^%"<-function(M, pow) { if (prod(dim(M)==list(1,1))) return( as.matrix(M^pow) ) eigenM = eigen(M) return(eigenM$vectors%*%diag(c(eigenM$values)^pow)%*%t(eigenM$vectors)) } Trace<-function(X) { if (!is.matrix(X)) stop("Argument to Trace is not a matrix in pfc") return(sum(diag(X))) } if (is.null(fy)) {fy <- scale(y, TRUE, TRUE); numdir <- 1} r <- dim(fy)[2] X <- as.matrix(X) op <- dim(X) n <- op[1] p <- op[2] eff.numdir <- min(numdir, r, p) vnames <- dimnames(X)[[2]] if (is.null(vnames)) vnames <- paste("X", 1:p, sep="") if (p==1) return(onepfc(X=X, y=y, fy=fy, p, numdir.test)) Muhat <- apply(X, 2, mean) Xc <- scale(X, TRUE, FALSE) P_F <- fy%*%solve(t(fy)%*%fy)%*%t(fy) Sigmahat <- cov(X) Sigmahat_fit <- cov(P_F%*%X) Sigmahat_res <- Sigmahat - Sigmahat_fit if (structure=="iso") { iso <- function(i) { ev <- eigen(Sigmahat) ev.fit <- eigen(Sigmahat_fit) all_evalues <-ev.fit$values evalues <- all_evalues[1:i] sigma2hat <- Re(sum(ev$values)/p) Gammahat <- Re(matrix(ev.fit$vectors[,1:i], ncol=i)) dimnames(Gammahat) <- list(vnames, paste("Dir", 1:i, sep="")) Betahat <-Re(t(Gammahat)%*%t(Xc)%*%fy%*%solve(t(fy)%*%fy)) sigma2hat <- Re((sum(ev$values)-sum(evalues))/p) Deltahat <- sigma2hat*diag(1, p) dimnames(Deltahat) <- list(vnames, vnames) loglik <- - 0.5*n*p*(1+log(2*pi*sigma2hat)) numpar <- p + (p-i)*i + i*dim(fy)[2] + 1 aic <- -2*loglik + 2*numpar bic <- -2*loglik + log(n)*numpar return(list(Betahat=Betahat, Gammahat=Gammahat, Deltahat=Deltahat, evalues=evalues, loglik=loglik, aic=aic, bic=bic, numpar=numpar)) } if (identical(numdir.test, FALSE)) { out <- iso(eff.numdir) ans <- list(R=X%*%orthonorm(out$Gammahat), Muhat=Muhat, Betahat=out$Betahat, Gammahat=out$Gammahat, Deltahat=out$Deltahat, loglik=out$loglik, aic=out$aic, bic=out$bic, numpar=out$numpar, numdir=eff.numdir, evalues=out$evalues, structure="iso", y=y, fy=fy, Xc=Xc, call=match.call(expand.dots=TRUE), numdir.test=numdir.test) class(ans) <- "pfc" return(ans) } if (identical(numdir.test, TRUE)) { aic <- bic <- numpar <- loglik <- vector(length=eff.numdir+1) Betahat <- Deltahat <- Gammahat <-vector("list") # No fitting values (eff.numdir=0) ev <- eigen(Sigmahat) sigma2hat <- sum(ev$values)/p loglik[1] <- - 0.5*n*p*(1+log(2*pi*sigma2hat)) numpar[1] <- p + 1 aic[1] <- -2*loglik[1] + 2*numpar[1] bic[1] <- -2*loglik[1] + log(n)*numpar[1] for (i in 1:eff.numdir) { fit <- iso(i) Betahat[[i]] <-fit$Betahat Gammahat[[i]] <-fit$Gammahat Deltahat[[i]] <- fit$Deltahat loglik[i+1] <- fit$loglik numpar[i+1] <- fit$numpar aic[i+1] <- fit$aic bic[i+1] <- fit$bic } ans <- list(R=X%*%orthonorm(Gammahat[[eff.numdir]]), Muhat=Muhat, Betahat=Betahat, Gammahat=Gammahat, Deltahat=Deltahat, loglik=loglik, aic=aic, bic=bic, numpar=numpar, numdir=eff.numdir, model="pfc", evalues=fit$evalues, structure="iso", y=y, fy=fy, Xc=Xc, call=match.call(), numdir.test=numdir.test) class(ans)<- "pfc" return(ans) } } if (structure=="aniso") { aniso = function(X, y, fy, d, eps_aniso=1e-3, numdir.test) { vnames <- dimnames(X)[[2]] if (is.null(vnames)) vnames <- paste("X", seq_len(ncol(X)), sep="") op <- dim(X) n <- op[1] p <- op[2] # Initial Step fit <- pfc(X=X, y=y, fy=fy, numdir=d, structure="iso", numdir.test=numdir.test) if (identical(numdir.test, FALSE)) { Betahatx <- fit$Betahat Gammahatx <- fit$Gammahat Xc <- scale(X, TRUE, FALSE) - fy%*%t(Gammahatx%*%Betahatx) deltahat <- diag(cov(Xc)) repeat { Xnew = X%*%((1/sqrt(deltahat))*diag(p)) fit <- pfc(X=Xnew, y=y, fy=fy, numdir=d, structure="iso", numdir.test=FALSE) Betahatx <- fit$Betahat Gammahatx <- (diag(p)*sqrt(deltahat))%*%fit$Gammahat Xc <- scale(X, TRUE, FALSE) - fy%*%t(Gammahatx%*%Betahatx) deltahat0 <- diag(t(Xc)%*%(Xc)/n) if (sum(abs(deltahat-deltahat0)) < eps_aniso) break deltahat <- deltahat0 } dimnames(Gammahatx) <- list(vnames, paste("Dir", 1:d, sep="")) Deltahat <- deltahat*diag(p) dimnames(Deltahat) <- list(vnames, vnames) loglik <- - 0.5*n*p*(1+log(2*pi)) - 0.5*n*log(prod(deltahat)) numpar <- p + d*(p-d) + ncol(fy)*d + p aic <- -2*loglik + 2*numpar bic <- -2*loglik + log(n)*numpar ans <- list(Betahat=Betahatx, Gammahat=orthonorm(Gammahatx), Deltahat=Deltahat, evalues=fit$evalues, loglik=loglik, aic=aic, bic=bic, numpar=numpar, numdir.test=numdir.test) return(ans) } Deltahat <- Betahat <- Gammahat <- vector("list") aic <- bic <- numpar <- loglik <- vector(length=eff.numdir + 1) # No fitting values (eff.numdir=0) ev <- eigen(Sigmahat) loglik[1] <- - 0.5*n*p*(1+log(2*pi)) - 0.5*n*log(prod(ev$values)) numpar[1] <- p + p aic[1] <- -2*loglik[1] + 2*numpar[1] bic[1] <- -2*loglik[1] + log(n)*numpar[1] for (i in 1:eff.numdir) { Betahatx <- fit$Betahat[[i]] Gammahatx <- fit$Gammahat[[i]] Xc <- scale(X, TRUE, FALSE) - fy%*%t(Gammahatx%*%Betahatx) deltahat <- diag(t(Xc)%*%(Xc)/n) repeat { Xnew = X%*%((1/sqrt(deltahat))*diag(p)) fit2 <- pfc(X=Xnew, y=y, fy=fy, numdir=i, structure="iso", numdir.test=FALSE) Betahatx <- fit2$Betahat Gammahatx <- (diag(p)*sqrt(deltahat))%*%fit2$Gammahat Xc <- scale(X, TRUE, FALSE) - fy%*%t(Gammahatx%*%Betahatx) deltahat0 <- diag(t(Xc)%*%(Xc)/n) if (sum(abs(deltahat-deltahat0)) < eps_aniso) break deltahat <- deltahat0 } Deltahat[[i]] <- deltahat*diag(p) dimnames(Deltahat[[i]]) <- list(vnames, vnames) loglik[i+1] = - 0.5*n*p*(1+log(2*pi)) - 0.5*n*log(prod(deltahat)) numpar[i+1] <- p + (p-i)*i + i*dim(fy)[2] + p aic[i+1] <- -2*loglik[i+1] + 2*numpar[i+1] bic[i+1] <- -2*loglik[i+1] + log(n)*numpar[i+1] Betahat[[i]] <- Betahatx Gammahat[[i]] <- orthonorm(Gammahatx) dimnames(Gammahat[[i]]) <- list(vnames, paste("Dir", 1:i, sep="")) } ans <- list(Betahat=Betahat, Gammahat=Gammahat, Deltahat=Deltahat, evalues=fit2$evalues, loglik=loglik, aic=aic, bic=bic, numpar=numpar, numdir.test=numdir.test) return(ans) } fit <- aniso(X=X, y=y, fy=fy, d=eff.numdir, eps_aniso=eps_aniso, numdir.test=numdir.test) ans <- list(Muhat=Muhat, Betahat=fit$Betahat, Gammahat=fit$Gammahat, Deltahat=fit$Deltahat, model="pfc", loglik=fit$loglik, aic=fit$aic, bic=fit$bic, numpar=fit$numpar, numdir=eff.numdir, evalues=fit$evalues, structure="aniso", Xc=Xc, y=y, fy=fy, call=match.call(), numdir.test=fit$numdir.test) if (numdir.test==FALSE) ans$R <- X%*%orthonorm(((fit$Deltahat)%^%(-1))%*%fit$Gammahat) else ans$R <- X%*%orthonorm(((fit$Deltahat[[eff.numdir]])%^%(-1))%*%fit$Gammahat[[eff.numdir]]) class(ans)<- "pfc" return(ans) } if (structure=="unstr") { unstr<-function(i) { sqrt_Sigmahat_res <- Sigmahat_res%^%0.5 Inv_Sqrt_Sigmahat_res <- solve(sqrt_Sigmahat_res) lf_matrix <- Inv_Sqrt_Sigmahat_res%*%Sigmahat_fit%*%Inv_Sqrt_Sigmahat_res all_evalues <- eigen(lf_matrix, symmetric=T)$values evalues <- all_evalues[1:i] Vhat <- eigen(lf_matrix, symmetric=T)$vectors Vhati <- matrix(Vhat[,1:i], ncol=i) Gammahat <- (Sigmahat_res%^%0.5)%*%Vhati%*%solve((t(Vhati)%*%Sigmahat_res%*%Vhati)%^%0.5) dimnames(Gammahat)<- list(vnames, paste("Dir", 1:i, sep="")) Khat<-diag(0, p) if (i < min(ncol(fy),p)) {diag(Khat)[(i+1):min(ncol(fy), p )]<- all_evalues[(i+1):min(ncol(fy), p)]} Deltahat <- sqrt_Sigmahat_res%*%Vhat%*%(diag(p)+Khat)%*%t(Vhat)%*%sqrt_Sigmahat_res dimnames(Deltahat) <- list(vnames, vnames) Betahat <- ((t(Vhati)%*%Sigmahat_res%*%Vhati)%^%0.5)%*%t(Vhati)%*%solve(Sigmahat_res%^%0.5)%*%t(Xc)%*%fy%*% solve(t(fy)%*%fy) temp0 <- -(n*p/2)*(1 + log(2*pi)) temp1 <- -(n/2)*log(det(Sigmahat_res)) temp2 <- 0 if (i < min(ncol(fy),p)) temp2 <- -(n/2)*sum(log(1 + all_evalues[(i+1):p])) loglik <- temp0 + temp1 + temp2 numpar <- p + (p-i)*i + i*ncol(fy) + p*(p+1)/2 aic <- -2*loglik + 2*numpar bic <- -2*loglik + log(n)*numpar return(list(Betahat=Betahat, Gammahat=Gammahat, Deltahat=Deltahat, evalues=evalues, loglik=loglik, aic=aic, bic=bic, numpar=numpar)) } if (identical(numdir.test, FALSE)) { out <- unstr(eff.numdir) ans <- list(R=X%*%orthonorm(solve(out$Deltahat)%*%out$Gammahat), Muhat=Muhat, Betahat=out$Betahat, Gammahat=out$Gammahat, Deltahat=out$Deltahat, evalues=out$evalues, loglik=out$loglik, aic=out$aic, bic=out$bic, numpar=out$numpar, numdir=eff.numdir, model="pfc", structure="unstr", y=y, fy=fy, Xc=Xc, call=match.call(), numdir.test=numdir.test) class(ans) <- "pfc" return(ans) } aic <- bic <- numpar <- loglik <- vector(length=eff.numdir+1) evalues <- vector(length=eff.numdir) Betahat <- Deltahat <- Gammahat <-vector("list") loglik[1] <- - 0.5*n*p*(1+log(2*pi)) - 0.5*n*log(det(Sigmahat)) numpar[1] <- p + p*(p+1)/2 aic[1] <- -2*loglik[1] + 2*numpar[1] bic[1] <- -2*loglik[1] + log(n)*numpar[1] Deltahat[[1]] <- Sigmahat dimnames(Deltahat[[1]]) <- list(vnames, vnames) for (i in 1:eff.numdir) { fit <- unstr(i) Betahat[[i]] <-fit$Betahat Gammahat[[i]] <-fit$Gammahat Deltahat[[i]] <- fit$Deltahat loglik[i+1] <- fit$loglik numpar[i+1] <- fit$numpar aic[i+1] <- fit$aic bic[i+1] <- fit$bic } ans <- list(R=X%*%orthonorm(solve(Deltahat[[eff.numdir]])%*%Gammahat[[eff.numdir]]), Muhat=Muhat, Betahat=Betahat, Gammahat=Gammahat, Deltahat=Deltahat, evalues=fit$evalues, loglik=loglik, aic=aic, bic=bic, numpar=numpar, numdir=eff.numdir, model="pfc", structure="unstr", y=y, fy=fy, Xc=Xc, call=match.call(), numdir.test=numdir.test) class(ans)<- "pfc" return(ans) } else if (structure=="unstr2") { unstr2 <- function(i) { objfun <- function(W) { Qt <- W$Qt dc <- W$dim[1] p <- ncol(Qt) S <- W$Sigmas U <- matrix(Qt[,1:dc], ncol=dc) V <- matrix(Qt[,(dc+1):p], ncol=(p-dc)) value <- -(n/2)*(p*log(2*pi)+p+log(det(t(V)%*%S$Sigmahat%*%V))+ log(det(t(U)%*%S$Sigmahat_res%*%U))) terme1 <- solve(t(U)%*%S$Sigmahat_res%*%U)%*%(t(U)%*%S$Sigmahat_res%*%V) terme2 <- (t(U)%*%S$Sigmahat%*%V)%*%solve(t(V)%*%S$Sigmahat%*%V) gradient <- 2*(terme1 - terme2) return(list(value=value, gradient=gradient)) } sigmas <- list(Sigmahat=Sigmahat, Sigmahat_fit=Sigmahat_fit, Sigmahat_res=Sigmahat_res, p=p, n=n) W <- list(Qt = svd(Sigmahat_fit)$u, dim=c(numdir, p), Sigmas=list(Sigmahat=Sigmahat, Sigmahat_fit=Sigmahat_fit, Sigmahat_res=Sigmahat_res, p=p, n=n)) objfun <- assign("objfun", objfun, envir=.BaseNamespaceEnv) grassoptim <- GrassmannOptim(objfun, W,...) Gammahat <- matrix(grassoptim$Qt[,1:i], ncol=i, dimnames=list(vnames, paste("Dir", 1:i, sep=""))) Gammahat0 <- matrix(grassoptim$Qt[, (i+1):p], ncol=p-i, dimnames=list(vnames, paste("Dir", (i+1):p, sep=""))) Betahat <- t(Gammahat)%*%t(Xc)%*%fy%*%solve(t(fy)%*%fy) Omegahat <- t(Gammahat)%*%Sigmahat_res%*%Gammahat Omegahat0 <-t(Gammahat0)%*%Sigmahat%*%Gammahat0 Deltahat <- Gammahat%*%Omegahat%*%t(Gammahat) + Gammahat0%*%Omegahat0%*%t(Gammahat0) dimnames(Deltahat) <- list(vnames, vnames) temp0 <- -(n*p/2)*(1+log(2*pi)) temp1 <- -(n/2)*log(det(t(Gammahat)%*%Sigmahat_res%*%Gammahat)) temp2 <- -(n/2)*log(det(t(Gammahat0)%*%Sigmahat%*%Gammahat0)) loglik <- temp0 + temp1 + temp2 numpar <- p + (p-i)*i + i*dim(fy)[2] + i*(i+1)/2 + (p-i)*(p-i+1)/2 aic <- -2*loglik + 2*numpar bic <- -2*loglik + log(n)*numpar ev.fit <- eigen(Sigmahat_fit) evalues <- ev.fit$values[1:i] return(list(Betahat=Betahat, Gammahat=Gammahat, Gammahat0=Gammahat0, Omegahat=Omegahat, Omegahat0=Omegahat0, Deltahat=Deltahat, evalues=evalues, loglik=loglik, aic=aic, bic=bic, numpar=numpar)) } if (identical(numdir.test, FALSE)) { out <- unstr2(numdir) ans <- list(R = X%*%out$Gammahat, Muhat=Muhat, Betahat=out$Betahat, Gammahat=out$Gammahat, Gammahat0=out$Gammahat0, Omegahat=out$Omegahat, Omegahat0=out$Omegahat0, Deltahat=out$Deltahat, evalues=out$evalues, loglik=out$loglik, aic=out$aic, bic=out$bic, numpar=out$numpar, numdir=numdir, model="pfc", structure="unstr2", y=y, fy=fy, Xc=Xc, call=match.call(), numdir.test=numdir.test) class(ans) <- "pfc" return(ans) } aic <- bic <- numpar <- loglik <- vector(length=numdir+1) Betahat <- Deltahat <- Gammahat <- Gammahat0 <- Omegahat <- Omegahat0 <- vector("list") loglik[1] <- -(n*p/2)*(log(2*pi) + (1+log(Trace(Sigmahat)/p))) numpar[1] <- p + p*(p+1)/2 aic[1] <- -2*loglik[1] + 2*numpar[1] bic[1] <- -2*loglik[1] + log(n)*numpar[1] for(m in 1:numdir) { fit <- unstr2(m) Betahat[[m]] <-fit$Betahat Gammahat[[m]] <-fit$Gammahat Omegahat[[m]] <- fit$Omegahat Omegahat0[[m]] <- fit$Omegahat0 Deltahat[[m]] <- fit$Deltahat loglik[m+1] <- fit$loglik numpar[m+1] <- fit$numpar aic[m+1] <- fit$aic bic[m+1] <- fit$bic } ans <- list(R = X%*%Gammahat[[numdir]], evalues=fit$evalues, loglik =loglik, aic=aic, bic=bic, numdir=numdir, numpar=numpar, Muhat=Muhat, Betahat=Betahat, Gammahat=Gammahat, Gammahat0=Gammahat0, Omegahat=Omegahat, Omegahat0=Omegahat0, Deltahat=Deltahat, model="pfc", structure="unstr2", y=y, fy=fy, Xc=Xc, call=match.call(), numdir.test=numdir.test) class(ans)<- "pfc" return(ans) } } #' @importFrom stats lm as.formula #' onepfc <- function(X, y, fy, p, numdir.test) { # X is univariate predictor nobs <- length(X) r <- dim(fy)[2] P_F <- fy %*% solve(t(fy) %*% fy) %*% t(fy) Xc <- scale(X, TRUE, FALSE) Sigmahat_fit <- (1/nobs)*t(Xc) %*% P_F %*% (Xc) ev.fit <- eigen(Sigmahat_fit) temp.dat <- data.frame(cbind(X, fy)) xnam <- paste("xx", 1:r, sep="") names(temp.dat) <- c("yy", xnam) fm.lm <- as.formula( paste("yy ~ ", paste(xnam, collapse= "+"))) summary.fm <- summary(lm(fm.lm, data=temp.dat)) Betahat <- matrix(summary.fm$coefficients[2:(r+1),1], ncol=r) Gammahat <- matrix(1, ncol=1, nrow=1) Deltahat <- matrix(summary.fm$sigma^2, ncol=1, nrow=1) Muhat <- matrix(summary.fm$coefficients[1,1], ncol=1) loglik <- - 0.5*n*(1+log(2*pi*summary.fm$sigma^2)) numpar <- p + dim(fy)[2] + 1 aic <- -2*loglik + 2*numpar bic <- -2*loglik + log(n)*numpar ans <- list(R=X, Muhat=Muhat, Betahat=Betahat, Gammahat=Gammahat, Deltahat=Deltahat, loglik=loglik, aic=aic, bic=bic, numpar=numpar, numdir=1, model="pfc", call=match.call(), structure="iso", y=y, fy=fy, Xc=Xc, numdir.test=numdir.test) class(ans)<- "pfc" return(ans) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/pfc.R
#' Plots EIB and EVPI for the Risk Aversion Case #' #' Summary plot of the health economic analysis when risk aversion is included. #' #' Plots the Expected Incremental Benefit and the Expected Value of Perfect Information #' when risk aversion is included in the utility function. #' #' @param x An object of the class `CEriskav`, a subclass of `bcea`, #' containing the results of the economic analysis performed accounting for a #' risk aversion parameter (obtained as output of the function [CEriskav()]). #' @template args-pos #' @param graph A string used to select the graphical engine to use for #' plotting. Should (partial-)match the two options `"base"` or #' `"ggplot2"`. Default value is `"base"`. #' @param ... Arguments to be passed to methods, such as graphical parameters #' (see [par()]). #' #' @return \item{list(eib,evi)}{A two-elements named list of the ggplot objects #' containing the requested plots. Returned only if `graph="ggplot2"`.} #' The function produces two plots for the risk aversion analysis. The first #' one is the EIB as a function of the discrete grid approximation of the #' willingness parameter for each of the possible values of the risk aversion #' parameter, `r`. The second one is a similar plot for the EVPI. #' #' @author Gianluca Baio, Andrea Berardi #' @seealso [bcea()], [CEriskav()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords hplot #' #' @importFrom grDevices dev.new devAskNewPage #' @importFrom grid unit #' @import ggplot2 #' #' @examples #' #' # See Baio G., Dawid A.P. (2011) for a detailed description of the #' # Bayesian model and economic problem #' # #' # Load the processed results of the MCMC simulation model #' data(Vaccine) #' # #' # Runs the health economic evaluation using BCEA #' m <- bcea(e=eff, c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e,c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000, # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0,Kmax) #' plot=FALSE # inhibits graphical output #' ) #' # #' # Define the vector of values for the risk aversion parameter, r, eg: #' r <- c(1e-10, 0.005, 0.020, 0.035) #' # #' # Run the cost-effectiveness analysis accounting for risk aversion #' \donttest{ #' CEriskav(m) <- r #' } #' # #' # produce the plots #' \donttest{ #' plot(m) #' } #' ## Alternative options, using ggplot2 #' \donttest{ #' plot(m, graph = "ggplot2") #' } #' #' @export #' plot.CEriskav <- function(x, pos = c(0, 1), graph = c("base", "ggplot2"), ...) { graph <- match.arg(graph) ##TODO: # graph_params <- prep_CEriskav_params(...) if (is_baseplot(graph)) { CEriskav_plot_base(x, pos) } else { CEriskav_plot_ggplot(x, pos) } }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/plot.CEriskav.R
#' Summary Plot of the Health Economic Analysis #' #' Plots in a single graph the Cost-Effectiveness plane, the Expected #' Incremental Benefit, the CEAC and the EVPI. #' #' The default position of the legend for the cost-effectiveness plane #' (produced by [ceplane.plot()]) is set to `c(1, 1.025)` #' overriding its default for `pos=FALSE`, since multiple ggplot2 plots #' are rendered in a slightly different way than single plots. #' #' @param x A `bcea` object containing the results of the Bayesian #' modelling and the economic evaluation. #' @template args-comparison #' @param wtp The value of the willingness to pay parameter. It is passed to #' [ceplane.plot()]. #' @template args-pos #' @param graph A string used to select the graphical engine to use for #' plotting. Should (partial-)match the two options `"base"` or #' `"ggplot2"`. Default value is `"base"`. #' @param ... Arguments to be passed to the methods [ceplane.plot()] #' and [eib.plot()]. Please see the manual pages for the individual #' functions. Arguments like `size`, `ICER.size` and `plot.cri` #' can be supplied to the functions in this way. In addition if #' `graph="ggplot2"` and the arguments are named theme objects they will #' be added to each plot. #' #' @return A plot with four graphical summaries of the health economic evaluation. #' #' @author Gianluca Baio, Andrea Berardi #' #' @seealso [bcea()], #' [ceplane.plot()], #' [eib.plot()], #' [ceac.plot()], #' [evi.plot()] #' @importFrom Rdpack reprompt #' @importFrom purrr map_lgl #' #' @references #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords hplot #' #' @examples #' # See Baio G., Dawid A.P. (2011) for a detailed description of the #' # Bayesian model and economic problem #' #' # Load the processed results of the MCMC simulation model #' data(Vaccine) #' #' # Runs the health economic evaluation using BCEA #' he <- bcea( #' e=eff, c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e,c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000, # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0,Kmax) #' plot=FALSE # does not produce graphical outputs #' ) #' #' # Plots the summary plots for the "bcea" object m using base graphics #' plot(he, graph = "base") #' #' # Plots the same summary plots using ggplot2 #' if(require(ggplot2)){ #' plot(he, graph = "ggplot2") #' #' ##### Example of a customized plot.bcea with ggplot2 #' plot(he, #' graph = "ggplot2", # use ggplot2 #' theme = theme(plot.title=element_text(size=rel(1.25))), # theme elements must have a name #' ICER_size = 1.5, # hidden option in ceplane.plot #' size = rel(2.5) # modifies the size of k = labels #' ) # in ceplane.plot and eib.plot #' } #' #' @import ggplot2 #' @export #' plot.bcea <- function(x, comparison = NULL, wtp = 25000, pos = FALSE, graph = c("base", "ggplot2"), ...) { ##TODO: where should this be used? # named_args <- c(as.list(environment()), list(...)) graph <- match.arg(graph) use_base_graphics <- pmatch(graph, c("base", "ggplot2")) != 2 extra_args <- list(...) # consistent colours across plots if (is.element("point", names(extra_args))) { if (is.element("color", names(extra_args$point))) { extra_args$line$color <- extra_args$point$color }} if (use_base_graphics) { withr::with_par(list(mfrow = c(2,2)), { ceplane.plot(x, comparison = comparison, wtp = wtp, pos = pos, graph = "base",...) do.call(eib.plot, c(he = list(x), pos = pos, comparison = comparison, graph = "base", extra_args)) do.call(ceac.plot, c(he = list(x), pos = pos, graph = "base", extra_args)) evi.plot(x, graph = "base", ...) }) } else { is_req_pkgs <- map_lgl(c("ggplot2","grid"), requireNamespace, quietly = TRUE) if (!all(is_req_pkgs)) { message("falling back to base graphics\n") plot.bcea( x, comparison = comparison, wtp = wtp, pos = pos, graph = "base", ...) return(invisible(NULL)) } if (all(is_req_pkgs)) { default_params <- list(text = element_text(size = 9), legend.key.size = grid::unit(0.5, "lines"), legend.spacing = grid::unit(-1.25, "line"), panel.grid = element_blank(), legend.key = element_blank(), plot.title = element_text( lineheight = 1, face = "bold", size = 11.5, hjust = 0.5)) keep_param <- names(default_params)[names(default_params) %in% names(extra_args)] extra_params <- extra_args[keep_param] global_params <- modifyList(default_params, extra_params, keep.null = TRUE) theme_add <- purrr::keep(extra_args, is.theme) ceplane.pos <- ifelse(pos, pos, c(1, 1.025)) ##TODO: warnings... ceplane <- ceplane.plot(x, wtp = wtp, pos = ceplane.pos, comparison = comparison, graph = "ggplot2", ...) + do.call(theme, global_params) + theme_add eib <- do.call(eib.plot, c(he = list(x), pos = pos, comparison = comparison, graph = "ggplot2", extra_args)) + do.call(theme, global_params) + theme_add ceac <- do.call(ceac.plot, c(he = list(x), pos = pos, comparison = comparison, graph = "ggplot2", extra_args)) + do.call(theme, global_params) + theme_add evi <- evi.plot(x, graph = "ggplot2", ...) + do.call(theme, global_params) + theme_add multiplot(list(ceplane, ceac, eib, evi), cols = 2) } } }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/plot.bcea.R
#' Plot Expected Value of Partial Information With Respect to a #' Set of Parameters #' #' @param x An object in the class `evppi`, #' obtained by the call to the function [evppi()]. #' @template args-pos #' @param graph A string used to select the graphical engine to use for #' plotting. Should (partial-) match the two options `"base"` or #' `"ggplot2"`. Default value is `"base"`. #' @param col Sets the colour for the lines depicted in the graph. #' @param ... Arguments to be passed to methods, such as graphical parameters #' (see [par()]). #' @return Plot with base R or \pkg{ggplot2}. #' #' @author Gianluca Baio, Andrea Berardi #' @seealso [bcea()], [evppi()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords hplot #' #' @export #' @examples #' #' \dontrun{ #' data(Vaccine, package = "BCEA") #' treats <- c("Status quo", "Vaccination") #' #' # Run the health economic evaluation using BCEA #' m <- bcea(e.pts, c.pts, ref = 2, interventions = treats) #' #' # Compute the EVPPI for a bunch of parameters #' inp <- createInputs(vaccine_mat) #' #' # Compute the EVPPI using INLA/SPDE #' if (require("INLA")) { #' x0 <- evppi(m, c("beta.1." , "beta.2."), input = inp$mat) #' #' plot(x0, pos = c(0,1)) #' #' x1 <- evppi(m, c(32,48,49), input = inp$mat) #' plot(x1, pos = "topright") #' #' plot(x0, col = c("black", "red"), pos = "topright") #' plot(x0, col = c(2,3), pos = "bottomright") #' #' plot(x0, pos = c(0,1), graph = "ggplot2") #' plot(x1, pos = "top", graph = "ggplot2") #' #' plot(x0, col = c("black", "red"), pos = "right", graph = "ggplot2") #' plot(x0, col = c(2,3), size = c(1,2), pos = "bottom", graph = "ggplot2") #' #' plot(x0, graph = "ggplot2", theme = ggplot2::theme_linedraw()) #' } #' #' if (FALSE) #' plot(x0, col = 3, pos = "topright") #' # The vector 'col' must have the number of elements for an EVPI #' # colour and each of the EVPPI parameters. Forced to black #' } #' plot.evppi <- function (x, pos = c(0, 0.8), graph = c("base", "ggplot2"), col = c(1, 1), ...) { graph <- match.arg(graph) if (is_baseplot(graph)) { evppi_plot_base(x, pos_legend = pos, col = col, ...) } else if (is_ggplot(graph)) { evppi_plot_ggplot(x, pos_legend = pos, col = col, ...) } else if (is_plotly(graph)) { ##TODO # evppi_plot_plotly(x, # pos_legend = pos, # graph_params) } }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/plot.evppi.R
#' @rdname BCEA-deprecated #' @section `plot.mixedAn`: #' For `plot.mixedAn`, use [evi.plot()]. #' #' Summary plot of the health economic analysis when the mixed analysis is #' considered #' #' Compares the optimal scenario to the mixed case in terms of the EVPI. #' #' @param x An object of class `mixedAn`, given as output of the call to #' the function [mixedAn()]. #' @param y.limits Range of the y-axis for the graph. The default value is #' `NULL`, in which case the maximum range between the optimal and the #' mixed analysis scenarios is considered. #' @param pos Parameter to set the position of the legend. Can be given in form #' of a string `(bottom|top)(right|left)` for base graphics and #' `bottom|top|left|right` for ggplot2. It can be a two-elements vector, #' which specifies the relative position on the x and y axis respectively, or #' alternatively it can be in form of a logical variable, with `FALSE` #' indicating to use the default position and `TRUE` to place it on the #' bottom of the plot. Default value is `c(0,1)`, that is in the topleft #' corner inside the plot area. #' @param graph A string used to select the graphical engine to use for #' plotting. Should (partial-)match the two options `"base"` or #' `"ggplot2"`. Default value is `"base"`. #' @param ... Arguments to be passed to methods, such as graphical parameters #' (see [par()]). #' @return \item{evi}{ A ggplot object containing the plot. Returned only if #' `graph="ggplot2"`. } The function produces a graph showing the #' difference between the ''optimal'' version of the EVPI (when only the most #' cost-effective intervention is included in the market) and the mixed #' strategy one (when more than one intervention is considered in the market). #' @author Gianluca Baio, Andrea Berardi #' @usage plot.mixedAn(x, y.limits=NULL, pos=c(0,1), graph=c("base","ggplot2"),...) #' #' @export #' plot.mixedAn <- function(x, y.limits = NULL, pos = c(0,1), graph = c("base","ggplot2"), ...) { .Deprecated(new = "evi.plot") }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/plot.mixedAn.R
#' Plot Credible Intervals #' #' Bayesian posterior credible intervals against willingness to pay. #' @template args-he #' @param params Graph parameters #' @importFrom graphics matlines #' @keywords internal #' plot_eib_cri <- function(he, params) { if (!params$plot.cri) return() ##TODO: move y rearranging to compute_eib_cri() ##TODO: single do.call() on combined y matrix do.call(matlines, list(x = he$k, y = matrix(params$data$low, ncol = he$n_comparisons), col = params$col, lty = params$lty)) do.call(matlines, list(x = he$k, y = matrix(params$data$upp, ncol = he$n_comparisons), col = params$col, lty = params$lty)) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/plot_eib_cri.R
#' Prepare CE-plane Parameters #' #' In ggplot format, combine user-supplied #' parameters with defaults. #' #' @template args-he #' @param wtp Willingness-to-pay #' @param ... Additional arguments #' @importFrom grDevices grey.colors #' #' @return List pf graph parameters #' @export #' @keywords internal #' prep_ceplane_params <- function(he, wtp, ...) { graph_params <- list(...) ##TODO: back-compatibility helper.. intervs_in_title <- paste("\n", he$interventions[he$ref], "vs", paste0(he$interventions[he$comp], collapse = ", ")) plot_title <- paste0( "Cost-Effectiveness Plane", ifelse(he$n_comparisons == 1, #he$change_comp, yes = intervs_in_title, no = "")) axes_lim <- xy_params(he, wtp, graph_params) default_params <- list(xlab = "Incremental effectiveness", ylab = "Incremental cost", title = plot_title, xlim = axes_lim$x, ylim = axes_lim$y, point = list( color = grey.colors(n = he$n_comparisons, end = 0.7, alpha = 1), size = 0.35, shape = rep(20, he$n_comparisons)), area_include = TRUE, ICER_size = 2, area = list( # line_color = "black", col = "grey95"), ref_first = TRUE) modifyList(default_params, graph_params) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/prep_ceplane_params.R
# prep_contour_params <- function(he, ...) { contour_params <- list(...) ceplane_params <- prep_ceplane_params(he, wtp = 1e7, ...) default_params <- modifyList(ceplane_params, list(scale = 0.5, nlevels = NULL, levels = c(0.25, 0.5, 0.75, 0.95))) modifyList(default_params, contour_params) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/prep_contour_params.R
#' Prepare EIB plot parameters #' #' Parameters general to all plotting devices. #' #' @template args-he #' @param plot.cri Make title including credible interval? Logical #' @param ... Additional parameters #' @return List of graph parameters #' @keywords internal #' prep_eib_params <- function(he, plot.cri, ...) { graph_params <- list(...) ##TODO: what is this?... # # if existing, read and store graphical options # aes_cat <- strsplit(aes_arg, "_")[[1]][1] # aes_name <- paste0(strsplit(aes_arg, "_")[[1]][-1], collapse = "_") # plot_aes[[aes_cat]][[aes_name]] <- exArgs[[aes_arg]] default_params <- list( xlab = "Willingness to pay", ylab = "EIB", alpha_cri = 0.05, cri.quantile = TRUE, area = list(include = FALSE, color = "grey"), labels = line_labels(he), line = list( type = rep_len(1:6, he$n_comparisons), lwd = ifelse(he$n_comparisons > 6, 1.5, 1), color = 1, #1:he$n_comparisons, cri_col = "grey50", cri_lty = 2), plot.cri = ifelse((is.null(plot.cri) && he$n_comparisons == 1) || (!is.null(plot.cri) && plot.cri), TRUE, FALSE)) graph_params <- modifyList(default_params, graph_params) graph_params$main <- paste0( "Expected Incremental Benefit", ifelse( default_params$plot.cri, paste0("\nand ", format((1 - graph_params$alpha_cri)*100, digits = 4), "% credible intervals"), "")) graph_params <- validate_eib_params(graph_params) graph_params } #' Validate EIB parameters #' #' @param params Graph parameters #' @seealso [prep_eib_params()] #' @return List of graph parameters #' @importFrom cli cli_alert_warning #' @keywords internal #' validate_eib_params <- function(params) { if (params$alpha_cri < 0 || params$alpha_cri > 1) { cli::cli_alert_warning( "Argument {.var alpha} must be between 0 and 1. Reset to default value 0.95.") params$alpha_cri <- 0.05 } if (params$alpha_cri > 0.8 && params$cri.quantile) { cli::cli_alert_warning( "It is recommended adopting the normal approximation of the credible interval for high values of {.var alpha}. Please set the argument {.code cri.quantile = FALSE} to use the normal approximation.") } params }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/prep_eib_params.R
#' Prepare frontier data #' #' @template args-he #' @param threshold Cost-effectiveness threshold i.e angle of line. Must be >=0 or NULL. #' @param start.origin Where should the frontier start from? #' @return List with scatter.data, ceef.points, orig.avg #' @seealso ceef.plot #' @importFrom cli cli_alert_warning #' @keywords internal #' prep_frontier_data <- function(he, threshold = NULL, start.origin = TRUE) { ## if threshold is NULL, then bound to pi/2, which is atan(Inf) ## else if positive, bound to the increase angle given the slope if (is.null(threshold)) { threshold <- pi/2 } else { if (threshold <= 0) { cli::cli_alert_warning( "The value of the cost-effectiveness threshold should be positive. The argument will be ignored.") threshold <- pi/2 } else { threshold <- atan(threshold) } } ## quick fix: he$e <- he$e[, c(he$comp, he$ref)] he$c <- he$c[, c(he$comp, he$ref)] # if the effectiveness is negative or # !start.origin then rescale # drop names means_e <- `names<-`(apply(he$e, 2, mean), NULL) means_c <- `names<-`(apply(he$c, 2, mean), NULL) ec_min <- c(mean_e = min(means_e), mean_c = means_c[which.min(means_e)], interv = which.min(means_e)) e.neg <- ec_min["mean_e"] < 0 c.neg <- any(means_c < 0) if (e.neg && !c.neg && start.origin) { message("Benefits are negative, the frontier will not start from the origins") start.origin <- FALSE } if (!e.neg && c.neg && start.origin) { message("Costs are negative, the frontier will not start from the origins") start.origin <- FALSE } if (e.neg && c.neg && start.origin) { message("Costs and benefits are negative, the frontier will not start from the origins") start.origin <- FALSE } # frontier calculation data.avg <- data.frame( "e.avg" = means_e - ifelse(start.origin, ec_min["mean_e"], 0), "c.avg" = means_c - ifelse(start.origin, ec_min["mean_c"], 0)) orig.avg <- cbind(data.avg, as.factor(c(he$comp, he$ref))) names(orig.avg) <- c("e.orig", "c.orig", "comp") data.avg <- cbind(data.avg, orig.avg) ##TODO: where should this be used? ##TODO: should this check if ALL interventions are 0? # check for interventions with zero costs and effectiveness # ce_zeros <- # xor(data.avg["e.avg"] == 0, # data.avg["c.avg"] == 0) # # comp <- # ifelse(any(ce_zeros), # yes = which(ce_zeros), # no = 0) # contains the points connecting the frontier # always starts from the origin ceef.points <- data.frame( x = 0, y = 0, comp = 0) ##TODO: new code # repeat { # no_data <- prod(dim(data.avg)) == 0 # # if (no_data) break # # slope <- atan(data.avg$c.avg/data.avg$e.avg) # slope.min <- min(slope, na.rm = TRUE) # # if (slope.min > threshold) break # # interv_idx <- which(slope == slope.min) # # if (length(interv_idx) > 1) # interv_idx <- interv_idx[which.min(data.avg$e.avg[interv_idx])] # # ceef.points <- with(data.avg, # rbind(ceef.points, orig.avg[interv_idx, ])) # # # move origin to current (e,c) # data.avg[, c("e.avg", "c.avg")] <- # data.avg[, c("e.orig", "c.orig")] - # matrix(rep(as.numeric(data.avg[interv_idx, c("e.orig", "c.orig")]), # nrow(data.avg)), # ncol = 2, # byrow = TRUE) # # data.avg <- subset(data.avg, c.avg*e.avg > 0 & c.avg + e.avg > 0) # } #### OLD CODE repeat { if (prod(dim(data.avg)) == 0) break theta <- atan(data.avg$c.avg/data.avg$e.avg) theta.min <- min(theta, na.rm = TRUE) if (theta.min > threshold) break index <- which(theta == theta.min) if (length(index) > 1) index <- index[which.min(data.avg$e.avg[index])] ceef_orig_idx <- c(data.avg$e.orig[index], data.avg$c.orig[index], data.avg$comp[index]) ceef.points <- rbind(ceef.points, ceef_orig_idx) rep_dataavg <- rep(as.numeric(data.avg[index, 3:4]), dim(data.avg)[1]) data.avg[, 1:2] <- data.avg[, 3:4] - matrix(rep_dataavg, ncol = 2, byrow = TRUE) pos_prod <- dplyr::filter(data.avg, .data$c.avg*.data$e.avg > 0) data.avg <- dplyr::filter(pos_prod, .data$c.avg + .data$e.avg > 0) } ############## ceef.points$comp <- factor(ceef.points$comp) ceef.points$slope <- NA ## calculate slopes for (i in 2:dim(ceef.points)[1]) { ceef.points$slope[i] <- (ceef.points$y[i] - ceef.points$y[i - 1])/(ceef.points$x[i] - ceef.points$x[i - 1]) } ## workaround for start.origin == FALSE: remove first row if slope is negative while (dim(ceef.points)[1] > 1 && ceef.points$slope[2] < 0) { ceef.points <- ceef.points[-1, ] ceef.points$slope[1] <- NA } # points scatter.data <- data.frame( e = c(he$e) - ifelse(!start.origin, 0, ec_min["mean_e"]), c = c(he$c) - ifelse(!start.origin, 0, ec_min["mean_c"]), comp = as.factor(rep(c(he$comp, he$ref), each = he$n_sim))) ## re-adjustment of data sets ceef.points[, "x"] <- ceef.points[, "x"] #+ ifelse(!e.neg, 0, ec_min["mean_e"]) ceef.points[, "y"] <- ceef.points[, "y"] #+ ifelse(!e.neg, 0, ec_min["mean_c"]) orig.avg[, "e.orig"] <- orig.avg[, "e.orig"] #+ ifelse(!e.neg, 0, ec_min["mean_e"]) orig.avg[, "c.orig"] <- orig.avg[, "c.orig"] #+ ifelse(!e.neg, 0, ec_min["mean_c"]) list(scatter.data = scatter.data, ceef.points = ceef.points, orig.avg = orig.avg) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/prep_frontier_data.R
#' @keywords dplot #' prepare_ceac_params <- function(he, ...) { extra_params <- list(...) # defaults plot_params <- list(area = list(include = FALSE, color = NULL), line = list(color = "black", size = 1, type = 1:num_lines(he)), currency = "") annot_params <- list(title = "Cost Effectiveness Acceptability Curve", x = "Willingness to pay", y = "Probability of cost effectiveness") plot_extra_params <- extra_params[c("area", "line", "currency")] annot_extra_params <- extra_params[c("title", "xlab", "ylab")] annot_params <- modifyList(annot_params, annot_extra_params) plot_params <- modifyList(plot_params, plot_extra_params) c(plot_params, list(annot = annot_params)) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/prepare_ceac_params.R
##TODO: I can't find where this is used?... # prepare_ceac_params_multi <- function(he, pos, ...) { alt.legend <- pos lty <- rep(1:6, ceiling(he$n_comparators/6))[1:he$n_comparators] label <- paste0(he$interventions) jus <- NULL if (alt.legend) { alt.legend <- "bottom" heplot <- heplot + theme(legend.direction = "vertical") } else { if (is.character(alt.legend)) { choices <- c("left", "right", "bottom", "top") alt.legend <- choices[pmatch(alt.legend, choices)] jus <- "center" if (is.na(alt.legend)) alt.legend <- FALSE } if (length(alt.legend) > 1) jus <- alt.legend if (length(alt.legend) == 1 && !is.character(alt.legend)) { alt.legend <- c(1, 0.5) jus <- alt.legend } } list(jus = jus, alt.legend = alt.legend, label = label, lty = lty) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/prepare_ceac_params_multi.R
#' Quadrant Parameters #' requires just a single comparison group #' @keywords internal aplot #' quadrant_params <- function(he, params) { p.ne <- sum(he$delta_e > 0 & he$delta_c > 0) / he$n_sim p.nw <- sum(he$delta_e <= 0 & he$delta_c > 0) / he$n_sim p.sw <- sum(he$delta_e <= 0 & he$delta_c <= 0) / he$n_sim p.se <- sum(he$delta_e > 0 & he$delta_c <= 0) / he$n_sim list( cex = 0.8, offset = 1.0, adj = list(c(1,1), c(0,1),c(0,0), c(1,0)), p.ne = p.ne, p.nw = p.nw, p.sw = p.sw, p.se = p.se, m.e = params$xlim[1], M.e = params$xlim[2], m.c = params$ylim[1], M.c = params$ylim[2], t1 = paste("Pr(Delta[e]>0, Delta[c]>0)==", format(p.ne, digits = 4, nsmall = 3), sep = ""), t2 = paste("Pr(Delta[e]<=0, Delta[c]>0)==", format(p.nw, digits = 4, nsmall = 3), sep = ""), t3 = paste("Pr(Delta[e]<=0, Delta[c]<=0)==", format(p.sw, digits = 4, nsmall = 3), sep = ""), t4 = paste("Pr(Delta[e]>0, Delta[c]<=0)==", format(p.se, digits = 4, nsmall = 3), sep = "")) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/quadrant_params.R
#' Choose Graphical Engine #' #' From base R, ggplot2 or plotly. #' #' @param graph Type names; string #' @return Plot ID integer 1:base R; 2:ggplot2; 3:plotly #' @importFrom cli cli_alert_warning #' @importFrom purrr map_lgl #' @keywords dplot internal #' select_plot_type <- function(graph) { if (missing(graph)) graph <- "base" graph_lup <- c(base = 1, ggplot2 = 2, plotly =3) graph_type <- graph_lup[graph] is_req_pkgs <- purrr::map_lgl(c("ggplot2", "grid"), requireNamespace, quietly = TRUE) if (graph_type == 2 && !all(is_req_pkgs)) { cli::cli_alert_warning( "Packages {.pkg ggplot2} and {.pkg grid} not found; plot will be rendered using base graphics.") graph_type <- 1} if (graph_type == 3 && !requireNamespace("plotly", quietly = TRUE)) { cli::cli_alert_warning( "Package {.pkg plotly} not found; plot will be rendered using base graphics.") graph_type <- 1} graph_type } #' is_baseplot <- function(graph) { select_plot_type(graph) == 1 } #' is_ggplot <- function(graph) { select_plot_type(graph) == 2 } #' is_plotly <- function(graph) { select_plot_type(graph) == 3 } ##TODO: this is from eib.plot() ## do we need to change anything? ## # # choose graphical engine # if (any(is.null(graph)) || any(is.na(graph))) graph <- "base" # # graph_choice <- pmatch(graph[1], c("base", "ggplot2", "plotly"), nomatch = 1) # # if (graph_choice == 2 && # !requireNamespace("ggplot2", quietly = TRUE) & # requireNamespace("grid", quietly = TRUE)) { # warning("Package ggplot2 and grid not found; # eib.plot will be rendered using base graphics.") # graph_choice <- 1 # } # if (graph_choice == 3 && # !requireNamespace("plotly", quietly = TRUE)) { # warning("Package plotly not found; # eib.plot will be rendered using base graphics.") # graph_choice <- 1 # }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/select_plot_type.R
#' @name setComparisons #' @title Set Comparisons Group #' #' @description One of the alternative way to set (e,c) comparison group. #' Simply recompute all comparisons and drop unwanted. #' #' @template args-he #' @template args-comparison #' @seealso [setComparisons<-()] #' @export #' setComparisons <- function(he, comparison) { if (is.null(comparison)) return(he) if (he$ref %in% comparison) stop("Can't select Reference group. Change Reference first.", call. = FALSE) n_interv <- ncol(he$e) if (any(!comparison %in% 1:n_interv)) stop("Comparison index not in available comparisons.", call. = FALSE) res <- bcea(eff = he$e, cost = he$c, ref = he$ref, interventions = he$interventions, Kmax = he$Kmax, k = he$k) name_comp <- he$interventions[comparison] res$comp <- comparison res$n_comparisons <- length(comparison) res$n_comparators <- length(comparison) + 1 res$delta_e <- res$delta_e[, name_comp, drop = FALSE] res$delta_c <- res$delta_c[, name_comp, drop = FALSE] res$ICER <- res$ICER[name_comp] res$ib <- res$ib[, , name_comp, drop = FALSE] res$eib <- res$eib[, name_comp, drop = FALSE] res$ceac <- res$ceac[, name_comp, drop = FALSE] ##TODO: is there a way not to recompute the whole thing? res$best <- best_interv_given_k(res$eib, res$ref, res$comp) res$kstar <- compute_kstar(res$k, res$best, res$ref) ##TODO: currently compute _all_ interventions in compute_U() ## change to this? # res$U <- res$U[, , name_comp, drop = FALSE] return(res) } #' @name setComparisons_assign #' @title Set Comparison Group #' #' @description One of the alternative way to set (e,c) comparison group. #' #' @template args-he #' @param value Comparison #' @return bcea-type object #' @seealso [setComparisons()] #' @export #' 'setComparisons<-' <- function(he, value) { UseMethod('setComparisons<-', he) } #' @rdname setComparisons_assign #' @export #' 'setComparisons<-.bcea' <- function(he, value) { setComparisons(he, value) } #' @rdname setComparisons_assign #' @export #' 'setComparisons<-.default' <- function(he, value) { stop("No method available.") }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/setComparisons.R
#' @rdname sim_table #' @export #' sim_table <- function(he, ...) UseMethod("sim_table", he) #' Table of Simulation Statistics for the Health Economic Model #' #' Using the input in the form of MCMC simulations and after having run the #' health economic model, produces a summary table of the simulations from the #' cost-effectiveness analysis. #' #' @template args-he #' @param wtp The value of the willingness to pay threshold to be used in the #' summary table. #' @param ... Additional arguments #' #' @return Produces the following elements: #' \item{table}{A table with simulation statistics from the economic model} #' \item{names.cols}{A vector of labels to be associated with each column of the table} #' \item{wtp}{The selected value of the willingness to pay} #' \item{idx_wtp}{The index associated with the selected value of the willingness #' to pay threshold in the grid used to run the analysis} #' #' @author Gianluca Baio #' @seealso [bcea()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords print #' @import dplyr #' #' @examples #' # See Baio G., Dawid A.P. (2011) for a detailed description of the #' # Bayesian model and economic problem #' #' # Load the processed results of the MCMC simulation model #' data(Vaccine) #' #' # Runs the health economic evaluation using BCEA #' m <- bcea(e=eff, # defines the variables of #' c=cost, # effectiveness and cost #' ref=2, # selects the 2nd row of (e, c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000) # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0, Kmax) #' #' # Now can save the simulation exercise in an object using sim_table() #' sim_table(m, # uses the results of the economic evaluation #' wtp=25000) # selects the particular value for k #' #' @export #' @rdname sim_table #' sim_table.bcea <- function(he, wtp = 25000, ...) { wtp <- min(wtp, he$Kmax) if (!is.element(wtp, he$k)) { if (!is.na(he$step)) { # The user has selected a non-acceptable value for wtp, # but has not specified wtp in the call to bcea stop( sprintf("The willingness to pay parameter is defined in the interval [0- %f], with increments of %f \n", he$Kmax, he$step), call. = FALSE) } else { # The user has actually specified wtp as input in the call to bcea he_k <- paste(he$k, collapse = " ") stop( paste0("The willingness to pay parameter is defined as:\n[", he_k, "] \nPlease select a suitable value", collapse = " "), call. = FALSE) } } # specific willingness to pay table <- cbind.data.frame( U = U_filter_by(he, wtp), Ustar = Ustar_filter_by(he, wtp), ib = ib_filter_by(he, wtp), ol = ol_filter_by(he, wtp), vi = vi_filter_by(he, wtp)) table <- bind_rows(table, summarise_all(table, mean)) # # use intervention names # U_cols <- grepl(pattern = paste0("^U\\.", he$interventions, collapse = "|"), names(table)) # U_names <- names(table)[U_cols] U_names <- paste0("U", seq_along(he$interventions)) names.cols <- c(U_names, "U*", paste0("IB", he$ref, "_", he$comp), "OL", "VI") colnames(table) <- names.cols rownames(table) <- c(1:he$n_sim, "Average") list( Table = table, names.cols = names.cols, wtp = wtp, ind.table = which(he$k == wtp)) } #' @export #' sim_table.default <- function(he, ...) { stop("No method for this object. Run bcea().", call. = FALSE) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/sim_table.R
#' Structural Probability Sensitivity Analysis #' #' Computes the weights to be associated with a set of competing models in #' order to perform structural PSA. #' #' The model is a list containing the output from either R2jags or #' R2WinBUGS for all the models that need to be combined in the model average #' effect is a list containing the measure of effectiveness computed from the #' various models (one matrix with n_sim x n_ints simulations for each model) #' cost is a list containing the measure of costs computed from the various #' models (one matrix with n_sim x n_ints simulations for each model). #' #' @param models A list containing the output from either R2jags or #' R2WinBUGS for all the models that need to be combined in the model average #' @param effect A list containing the measure of effectiveness computed from #' the various models (one matrix with n.sim x n.ints simulations for each #' model) #' @param cost A list containing the measure of costs computed from the various #' models (one matrix with n.sim x n.ints simulations for each model) #' @param ref Which intervention is considered to be the reference #' strategy. The default value `ref=1` means that the intervention #' appearing first is the reference and the other(s) is(are) the comparator(s) #' @param interventions Defines the labels to be associated with each #' intervention. By default and if `NULL`, assigns labels in the form #' "Intervention1", ... , "InterventionT" #' @param Kmax Maximum value of the willingness to pay to be considered. #' Default value is `50000`. The willingness to pay is then approximated #' on a discrete grid in the interval `[0, Kmax]`. The grid is equal to #' `k` if the parameter is given, or composed of `501` elements if #' `k=NULL` (the default) #' @param plot A logical value indicating whether the function should produce #' the summary plot or not #' @param w A vector of weights. By default it's NULL to indicate that the #' function will calculate the model weights based on DIC and the individual #' model fit. This behaviour can be overridden by passing a vector `w`, #' for instance based on expert opinion #' #' @return List object of bcea object, model weights and DIC #' @author Gianluca Baio #' @seealso [bcea()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2013}{BCEA} #' #' @export #' #' @examples #' #' \dontrun{ #' # load sample jags output #' load(system.file("extdata", "statins_base.RData", package = "BCEA")) #' load(system.file("extdata", "statins_HC.RData", package = "BCEA")) #' #' interventions <- c("Atorvastatin", "Fluvastatin", #' "Lovastatin", "Pravastatin", #' "Rosuvastatin", "Simvastatin") #' #' m1 <- bcea(eff = statins_base$sims.list$effect, #' cost = statins_base$sims.list$cost.tot, #' ref = 1, interventions = interventions) #' #' m2 <- bcea(eff = statins_HC$sims.list$effect, #' cost = statins_HC$sims.list$cost.tot, #' ref = 1, interventions = interventions) #' #' models <- list(statins_base, statins_HC) #' #' effects <- list(statins_base$sims.list$effect, #' statins_HC$sims.list$effect) #' costs <- list(statins_base$sims.list$cost.tot, #' statins_HC$sims.list$cost.tot) #' #' m3 <- struct.psa(models, effects, costs, #' ref = 1, interventions = interventions) #' } #' struct.psa <- function(models, effect, cost, ref = NULL, interventions = NULL, Kmax = 50000, plot = FALSE, w=NULL) { if (is.null(ref)) { ref <- 1 message("No reference selected. Defaulting to first intervention.") } n_models <- length(models) if (n_models == 1) { stop("Need at least two models to run structural PSA", call. = FALSE) } d <- numeric() mdl <- list() for (i in seq_len(n_models)) { # 1. checks whether each model has been run using JAGS or BUGS if (inherits(models[[i]], "rjags")) { mdl[[i]] <- models[[i]]$BUGSoutput } if (inherits(models[[i]], "bugs")) { mdl[[i]] <- models[[i]] } # 2. saves the DIC in vector d mdl[[i]] <- models[[i]] d[i] <- mdl[[i]]$DIC } dmin <- min(d) # minimum value to re-scale DICs delta_dic <- abs(dmin - d) # Only compute w using DIC if the user hasn't passed a suitable value if (is.null(w)) { w <- exp(-0.5*(delta_dic))/sum(exp(-0.5*(delta_dic))) # model weights (cfr BMHE) } if ((!is.null(w) & length(w) != n_models)) { stop("If you are considering user-defined weights, you must pass a vector whose length is the same as the number of models to average!") } # weights the simulations for the variables of effectiveness and costs in each model # using the respective weights, to produce the economic analysis for the average model e <- c <- matrix(NA, nrow = dim(effect[[1]])[1], ncol = dim(effect[[1]])[2]) e <- w[1]*effect[[1]] c <- w[1]*cost[[1]] for (i in 2:n_models) { e <- e + w[i]*effect[[i]] c <- c + w[i]*cost[[i]] } # perform economic analysis on averaged model he <- bcea(eff = e, cost = c, ref = ref, interventions = interventions, Kmax = Kmax, plot = plot) res <- c(he, list(w = w, DIC = d)) structure(res, class = c("struct.psa", class(he))) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/struct.psa.R
#' Summary Method for Objects of Class `bcea` #' #' Produces a table printout with some summary results of the health economic #' evaluation. #' #' @param object A `bcea` object containing the results of the Bayesian #' modelling and the economic evaluation. #' @param wtp The value of the willingness to pay threshold used in the summary table. #' @param ... Additional arguments affecting the summary produced. #' #' @return Prints a summary table with some information on the health economic #' output and synthetic information on the economic measures (EIB, CEAC, EVPI). #' @author Gianluca Baio #' @seealso [bcea()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords print #' #' @export #' #' @examples #' data(Vaccine) #' #' he <- bcea(eff, cost, interventions = treats, ref = 2) #' summary(he) #' summary.bcea <- function(object, wtp = 25000,...) { he <- object if (max(he$k) < wtp) { wtp <- max(he$k) message( cat(paste0( "NB: k (wtp) is defined in the interval [", min(he$k), " - ", wtp, "]\n"))) } if (!is.element(wtp, he$k)) { if (!is.na(he$step)) { # The user has selected a non-acceptable value for wtp, # but has not specified wtp in the call to bcea stop( paste0( "The willingness to pay parameter is defined in the interval [0-", he$Kmax, "], with increments of ", he$step, "\n"), call. = FALSE) } else { # The user has actually specified wtp as input in the call to bcea he_k <- paste(he$k, collapse = " ") stop( paste0("The willingness to pay parameter is defined as:\n[", he_k, "]\nPlease select a suitable value", collapse = " "), call. = FALSE) } } Table <- sim_table(he, wtp = wtp)$Table EU_tab <- matrix(NA, he$n_comparators, 1, dimnames = list(NULL, "Expected net benefit")) # columns to keep U_cols <- is.element(names(Table), paste0("U", c(he$ref, he$comp))) interv_idx <- gsub(pattern = "^.", "", x = names(Table)[U_cols]) # average row EU_tab[, 1] <- unlist(Table[he$n_sim + 1, U_cols]) rownames(EU_tab) <- he$interventions[as.numeric(interv_idx)] comp_tab <- matrix(NA, he$n_comparisons, 3) comp_tab[, 1] <- unlist(Table[he$n_sim + 1, paste0("IB", he$ref, "_", he$comp)]) if (he$n_comparisons == 1) { comp_tab[, 2] <- sum(Table[1:he$n_sim, paste0("IB", he$ref, "_", he$comp)] > 0) / he$n_sim comp_tab[, 3] <- he$ICER } if (he$n_comparisons > 1) { for (i in seq_len(he$n_comparisons)) { comp_tab[i, 2] <- sum(Table[1:he$n_sim, paste0("IB", he$ref, "_", he$comp[i])] > 0) / he$n_sim comp_tab[i, 3] <- he$ICER[i] } } colnames(comp_tab) <- c("EIB", "CEAC", "ICER") rownames(comp_tab) <- paste0(he$interventions[he$ref], " vs ", he$interventions[he$comp]) evpi_tab <- matrix(NA, 1, 1) evpi_tab[, 1] <- Table[he$n_sim + 1, "VI"] rownames(evpi_tab) <- "EVPI" #TODO: this is different value to book?? colnames(evpi_tab) <- "" ## prints the summary table cat("\n") cat("Cost-effectiveness analysis summary \n") cat("\n") cat(paste0("Reference intervention: ", he$interventions[he$ref], "\n")) # cat(paste0("Reference intervention: ", green(he$interventions[he$ref]), "\n")) if (he$n_comparisons == 1) { cat( paste0("Comparator intervention: ", he$interventions[he$comp], # green(he$interventions[he$comp]), "\n")) } if (he$n_comparisons > 1) { cat( paste0("Comparator intervention(s): ", he$interventions[he$comp[1]], "\n")) for (i in 2:he$n_comparisons) { cat(paste0(" : ", he$interventions[he$comp[i]], "\n")) # cat(paste0(" : ", green(he$interventions[he$comp[i]]), "\n")) } } cat("\n") if (length(he$kstar) == 0 && !is.na(he$step)) { cat( paste0( he$interventions[he$best[1]], " dominates for all k in [", min(he$k), " - ", max(he$k), "] \n")) } if (length(he$kstar) == 1 && !is.na(he$step)) { ##TODO: why recalc when same as he$kstar? kstar <- he$k[which(diff(he$best) != 0) + 1] cat( paste0( "Optimal decision: choose ", he$interventions[he$best[1]], " for k < ", kstar, " and ", he$interventions[he$best[he$k == kstar]], " for k >= ", kstar, "\n")) } if (length(he$kstar) > 1 && !is.na(he$step)) { cat( paste0( "Optimal decision: choose ", he$interventions[he$best[he$k == he$kstar[1] - he$step]], " for k < ", he$kstar[1], "\n")) for (i in 2:length(he$kstar)) { cat(paste0( " ", he$interventions[he$best[he$k == he$kstar[i] - he$step]], " for ", he$kstar[i - 1], " <= k < ", he$kstar[i], "\n")) } cat(paste0( " ", he$interventions[he$best[he$k == he$kstar[length(he$kstar)]]], " for k >= ", he$kstar[length(he$kstar)], "\n")) } cat("\n\n") cat(paste0("Analysis for willingness to pay parameter k = ", wtp, "\n")) cat("\n") print(EU_tab, quote = FALSE, digits = 5, justify = "center") cat("\n") print(comp_tab, quote = FALSE, digits = 5, justify = "center") cat("\n") cat( paste0( "Optimal intervention (max expected net benefit) for k = ", wtp, ": ", he$interventions[he$best][he$k == wtp], "\n")) print(evpi_tab, quote = FALSE, digits = 5, justify = "center") invisible(he) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/summary.bcea.R
#' Summary Methods For Objects in the Class `mixedAn` (Mixed Analysis) #' #' Prints a summary table for the results of the mixed analysis for the #' economic evaluation of a given model. #' #' @param object An object of the class `mixedAn`, which is the results of #' the function [mixedAn()], generating the economic evaluation of a #' set of interventions, considering given market shares for each option. #' @param wtp The value of the willingness to pay chosen to present the analysis. #' @param ... Additional arguments affecting the summary produced. #' @return Produces a table with summary information on the loss in expected #' value of information generated by the inclusion of non cost-effective #' interventions in the market. #' @author Gianluca Baio #' @seealso [bcea()], #' [mixedAn()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2009}{BCEA} #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords print #' #' @examples #' #' # See Baio G., Dawid A.P. (2011) for a detailed description of the #' # Bayesian model and economic problem #' #' # Load the processed results of the MCMC simulation model #' data(Vaccine) #' #' # Runs the health economic evaluation using BCEA #' m <- bcea(e=eff, c=cost, # defines the variables of #' # effectiveness and cost #' ref=2, # selects the 2nd row of (e,c) #' # as containing the reference intervention #' interventions=treats, # defines the labels to be associated #' # with each intervention #' Kmax=50000 # maximum value possible for the willingness #' # to pay threshold; implies that k is chosen #' # in a grid from the interval (0,Kmax) #' ) #' #' mixedAn(m) <- NULL # uses the results of the mixed strategy #' # analysis (a "mixedAn" object) #' # the vector of market shares can be defined #' # externally. If NULL, then each of the T #' # interventions will have 1/T market share #' #' # Prints a summary of the results #' summary(m, # uses the results of the mixed strategy analysis #' wtp=25000) # (a "mixedAn" object) #' # selects the relevant willingness to pay #' # (default: 25,000) #' #' @export #' summary.mixedAn <- function(object, wtp = 25000,...) { if (max(object$k) < wtp) { wtp <- max(object$k) } if (length(which(object$k == wtp)) == 0) { stop( paste0( "The willingness to pay parameter is defined in the interval [0-", object$Kmax, "], with increments of ", object$step, "\n") ) } n.digits <- 2 n.small <- 2 cat("\n") cat(paste0( "Analysis of mixed strategy for willingness to pay parameter k = ", wtp, "\n")) cat("\n") cat( paste0( "Reference intervention: ", object$interventions[object$ref], " (", format(100 * object$mkt.shares[object$ref], digits = n.digits, nsmall = n.small), "% market share)\n") ) if (object$n_comparisons == 1) { text.temp <- paste0( "Comparator intervention: ", object$interventions[object$comp], " (", format( 100 * object$mkt.shares[object$comp], digits = n.digits, nsmall = n.small), "% market share)\n") cat(text.temp) } if (object$n_comparisons > 1) { text.temp <- paste0( "Comparator intervention(s): ", object$interventions[object$comp[1]], " (", format( 100 * object$mkt.shares[object$comp[1]], digits = n.digits, nsmall = n.small), "% market share)\n") cat(text.temp) for (i in 2:object$n_comparisons) { cat(paste0( " : ", object$interventions[object$comp[i]], " (", format( 100 * object$mkt.shares[object$comp[i]], digits = n.digits, nsmall = n.small), "% market share)\n")) } } cat("\n") cat(paste0( "Loss in the expected value of information = ", format( object$evi.star[object$k == wtp] - object$evi[object$k == wtp], digits = n.digits, nsmall = n.small), "\n")) cat("\n") }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/summary.mixedAn.R
#' Summary Method for Objects of Class `pairwise` #' #' Produces a table printout with some summary results of the health economic #' evaluation. #' #' @param object A `pairwise` object containing the results of the Bayesian #' modelling and the economic evaluation. #' @param wtp The value of the willingness to pay threshold used in the #' summary table. #' @param ... Additional arguments affecting the summary produced. #' #' @return Prints a summary table with some information on the health economic #' output and synthetic information on the economic measures (EIB, CEAC, EVPI). #' @author Gianluca Baio #' @seealso [bcea()] [multi.ce()] #' @importFrom Rdpack reprompt #' #' @references #' #' \insertRef{Baio2011}{BCEA} #' #' \insertRef{Baio2013}{BCEA} #' #' @keywords print #' #' @export #' #' @examples #' data(Vaccine) #' he <- bcea(eff, cost, interventions = treats, ref = 2) #' he_multi <- multi.ce(he) #' summary(he_multi) #' summary.pairwise <- function(object, wtp = 25000,...) { he <- object if (max(he$k) < wtp) { wtp <- max(he$k) message( cat(paste0( "NB: k (wtp) is defined in the interval [", min(he$k), " - ", wtp, "]\n"))) } if (!is.element(wtp, he$k)) { if (!is.na(he$step)) { # The user has selected a non-acceptable value for wtp, # but has not specified wtp in the call to bcea stop( paste0( "The willingness to pay parameter is defined in the interval [0-", he$Kmax, "], with increments of ", he$step, "\n"), call. = FALSE) } else { # The user has actually specified wtp as input in the call to bcea he_k <- paste(he$k, collapse = " ") stop( paste0("The willingness to pay parameter is defined as:\n[", he_k, "]\nPlease select a suitable value", collapse = " "), call. = FALSE) } } Table <- sim_table(he, wtp = wtp)$Table ##TODO: where is p_best_interv in this order?? row_idx <- c(he$comp, he$ref) EU_tab <- matrix(NA, he$n_comparators, 4) EU_tab[row_idx, 1] <- unlist(Table[he$n_sim + 1, paste0("U", 1:he$n_comparators)]) colnames(EU_tab) <- c("Expected net benefit", "EIB", "CEAC", "ICER") rownames(EU_tab) <- he$interventions[row_idx] EU_tab[, 3] <- he$p_best_interv[he$k == wtp, ] evpi_tab <- matrix(NA, 1, 1) evpi_tab[, 1] <- Table[he$n_sim + 1, "VI"] rownames(evpi_tab) <- "EVPI" colnames(evpi_tab) <- "" ## prints the summary table cat("\n") cat("Cost-effectiveness analysis summary \n") cat("\n") cat( paste0("Intervention(s): ", he$interventions[1], "\n")) for (i in he$interventions[-1]) { cat(paste0(" : ", i, "\n")) } cat("\n") if (length(he$kstar) == 0 && !is.na(he$step)) { cat( paste0( he$interventions[he$best[1]], " dominates for all k in [", min(he$k), " - ", max(he$k), "] \n")) } if (length(he$kstar) == 1 & !is.na(he$step)) { kstar <- he$k[which(diff(he$best) == 1) + 1] cat( paste0( "Optimal decision: choose ", he$interventions[he$best[1]], " for k < ", kstar, " and ", he$interventions[he$best[he$k == kstar]], " for k >= ", kstar, "\n")) } if (length(he$kstar) > 1 && !is.na(he$step)) { cat( paste0( "Optimal decision: choose ", he$interventions[he$best[he$k == he$kstar[1] - he$step]], " for k < ", he$kstar[1], "\n")) for (i in 2:length(he$kstar)) { cat(paste0( " ", he$interventions[he$best[he$k == he$kstar[i] - he$step]], " for ", he$kstar[i - 1], " <= k < ", he$kstar[i], "\n")) } cat(paste0( " ", he$interventions[he$best[he$k == he$kstar[length(he$kstar)]]], " for k >= ", he$kstar[length(he$kstar)], "\n")) } cat("\n\n") cat(paste0("Analysis for willingness to pay parameter k = ", wtp, "\n")) cat("\n") print(EU_tab, quote = FALSE, digits = 5, justify = "center") cat("\n") cat( paste0( "Optimal intervention (max expected net benefit) for k = ", wtp, ": ", he$interventions[he$best][he$k == wtp], "\n")) print(evpi_tab, quote = FALSE, digits = 5, justify = "center") invisible(he) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/summary.pairwise.R
# themes for ggplot functions --------------------------------------------- #' bcea theme ggplot2 #' @name theme_bcea #' @keywords internal aplot #' theme_default <- function() { theme_bw() %+replace% theme(legend.title = element_blank(), legend.background = element_blank(), text = element_text(size = 11), legend.key.size = grid::unit(0.66, "lines"), legend.spacing = grid::unit(-1.25, "line"), panel.grid = element_blank(), legend.key = element_blank(), legend.text.align = 0, plot.title = element_text( lineheight = 1.05, face = "bold", size = 14.3, hjust = 0.5), complete = TRUE) } #' @rdname theme_bcea #' theme_ceac <- function() { theme_default() } #' @rdname theme_bcea #' theme_ceplane <- function() { theme_default() } #' @rdname theme_bcea #' theme_eib <- function() { theme_default() } #' @rdname theme_bcea #' theme_contour <- function() { theme_default() }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/themes_ggplot.R
#' Validate bcea #' #' @param eff Effectiveness matrix #' @param cost Cost matrix #' @param ref Reference intervention #' @param interventions All interventions #' #' @export #' @keywords internal #' validate_bcea <- function(eff, cost, ref, interventions) { if (!is.matrix(cost) || !is.matrix(eff)) stop("eff and cost must be matrices.", call. = FALSE) if (ncol(cost) == 1 || ncol(eff) == 1) stop("Require at least 2 comparators.", call. = FALSE) if (!is.null(interventions) && length(interventions) != ncol(eff)) stop("interventions names wrong length.", call. = FALSE) if (any(dim(eff) != dim(cost))) stop("eff and cost are not the same dimensions.", call. = FALSE) if (!is.numeric(ref) || ref < 1 || ref > ncol(eff)) stop("reference is not in available interventions.", call. = FALSE) return() }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/validate_bcea.R
##TODO: need to compare with master # xy_params <- function(he, wtp, graph_params) { e_dat <- he$delta_e c_dat <- he$delta_c min_e <- min(e_dat) max_e <- max(e_dat) min_c <- min(c_dat) max_c <- max(c_dat) # force negative min_e <- -abs(min_e) min_c <- -abs(min_c) # square plotting area min_e <- min(min_e, min_c/wtp) max_e <- max(max_e, max_c/wtp) # min_c <- min_e*wtp # max_c <- max_e*wtp list(xlim = c(min_e, max_e), ylim = c(min_c, max_c)) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/xy_params.R
.bcea_env <- new.env(parent = emptyenv()) .onLoad <- function(libname, pkgname) { op <- options() op.bcea <- list( scipen = 10) toset <- !(names(op.bcea) %in% names(op)) if (any(toset)) options(op.bcea[toset]) ps.options(encoding = "CP1250") pdf.options(encoding = "CP1250") Sys.setenv("_R_CHECK_LENGTH_1_CONDITION_" = "TRUE") invisible() } #' @title .onAttach #' @description prints out a friendly reminder message to the user #' @inheritParams base .onAttach #' @return NULL #' @noRd .onAttach <- function(libname, pkgname) { packageStartupMessage("The BCEA version loaded is: ", utils::packageVersion("BCEA")) }
/scratch/gouwar.j/cran-all/cranData/BCEA/R/zzz.R
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ## ----setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE---------- library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ## ----------------------------------------------------------------------------- data(Smoking) treats <- c("No intervention", "Self-help", "Individual counselling", "Group counselling") bcea_smoke <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) ## ----------------------------------------------------------------------------- r <- c(0, 0.005, 0.020, 0.035) CEriskav(bcea_smoke) <- r plot(bcea_smoke) plot(bcea_smoke, graph = "ggplot") ## ----------------------------------------------------------------------------- setComparisons(bcea_smoke) <- c(1,3) ## ----------------------------------------------------------------------------- CEriskav(bcea_smoke) <- r plot(bcea_smoke) plot(bcea_smoke, graph = "ggplot") ## ----------------------------------------------------------------------------- r <- 0 CEriskav(bcea_smoke) <- r plot(bcea_smoke) plot(bcea_smoke, graph = "ggplot") bcea_smoke0 <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) eib.plot(bcea_smoke0, comparison = 1) evi.plot(bcea_smoke0) ## ----------------------------------------------------------------------------- # negative r <- -0.005 CEriskav(bcea_smoke) <- r plot(bcea_smoke) # large r <- 2 CEriskav(bcea_smoke) <- r plot(bcea_smoke) ## ----------------------------------------------------------------------------- setComparisons(bcea_smoke) <- c(3,1) ## ----------------------------------------------------------------------------- r <- c(0, 0.005, 0.020, 0.035) CEriskav(bcea_smoke) <- r plot(bcea_smoke) plot(bcea_smoke, graph = "ggplot") ## ----------------------------------------------------------------------------- # base R plot(bcea_smoke, pos = c(1,0)) plot(bcea_smoke, pos = c(1,1)) plot(bcea_smoke, pos = TRUE) plot(bcea_smoke, pos = FALSE) plot(bcea_smoke, pos = "topleft") plot(bcea_smoke, pos = "topright") plot(bcea_smoke, pos = "bottomleft") plot(bcea_smoke, pos = "bottomright") # ggplot2 plot(bcea_smoke, graph = "ggplot", pos = c(1,0)) plot(bcea_smoke, graph = "ggplot", pos = c(1,1)) plot(bcea_smoke, graph = "ggplot", pos = TRUE) plot(bcea_smoke, graph = "ggplot", pos = FALSE) plot(bcea_smoke, graph = "ggplot", pos = "top") plot(bcea_smoke, graph = "ggplot", pos = "bottom") plot(bcea_smoke, graph = "ggplot", pos = "left") plot(bcea_smoke, graph = "ggplot", pos = "right") ## ----eval=FALSE, echo=FALSE--------------------------------------------------- # # create output docs # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "pdf_document", output_dir = "vignettes") # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "html_document", output_dir = "vignettes")
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/CEriskav.R
--- title: "Risk Aversion Analysis" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Risk Aversion Analysis} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ``` ```{r setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE} library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ``` Set-up analysis using smoking cessation data set. ```{r} data(Smoking) treats <- c("No intervention", "Self-help", "Individual counselling", "Group counselling") bcea_smoke <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) ``` Run the risk aversion analysis straight away with both the base R and ggplot2 versions of plots. ```{r} r <- c(0, 0.005, 0.020, 0.035) CEriskav(bcea_smoke) <- r plot(bcea_smoke) plot(bcea_smoke, graph = "ggplot") ``` Notice that the first value is asymptotically zero but the function handles that for us. Previously, you had to use something like 1e-10 which was a bit awkward. Now we modify the comparison group so that it doesn't contain 2 ("self-help") anymore. We still keep the same first comparison though "no intervention". ```{r} setComparisons(bcea_smoke) <- c(1,3) ``` If we rerun the analysis we should see that the output is exactly the same. ```{r} CEriskav(bcea_smoke) <- r plot(bcea_smoke) plot(bcea_smoke, graph = "ggplot") ``` What happens when we only have one risk adjustment value? Set it to zero so this should be exactly the same as the baseline `bcea` case. ```{r} r <- 0 CEriskav(bcea_smoke) <- r plot(bcea_smoke) plot(bcea_smoke, graph = "ggplot") bcea_smoke0 <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) eib.plot(bcea_smoke0, comparison = 1) evi.plot(bcea_smoke0) ``` Check that unusual or meaningless values for `r` are handled gracefully. At present the are just calculated and plotting exactly the same way. _should we limit values?_ ```{r} # negative r <- -0.005 CEriskav(bcea_smoke) <- r plot(bcea_smoke) # large r <- 2 CEriskav(bcea_smoke) <- r plot(bcea_smoke) ``` If we select a new set of comparison interventions what will happen? There are specified in a different order and for other plots this makes very little difference (perhaps changing the line types). However, it is different for `CEriskav()` because only the first comparison intervention is plotted so changing the order changes the plot. We can see this by swapping "non intervention" and "individual counselling" interventions from the analysis above. ```{r} setComparisons(bcea_smoke) <- c(3,1) ``` ```{r} r <- c(0, 0.005, 0.020, 0.035) CEriskav(bcea_smoke) <- r plot(bcea_smoke) plot(bcea_smoke, graph = "ggplot") ``` The previous version of `CEriskav()` had a `comparison` argument where you could specify the single intervention to plot and if this wasn't set then it defaulted to the first. It seems neater to separate the definition of the analysis with the plotting so now if you did want to specify a different comparison intervention when using `CEriskav()` then you would have to use `setComparison()` first and then call the plotting function. Check legend position argument: ```{r} # base R plot(bcea_smoke, pos = c(1,0)) plot(bcea_smoke, pos = c(1,1)) plot(bcea_smoke, pos = TRUE) plot(bcea_smoke, pos = FALSE) plot(bcea_smoke, pos = "topleft") plot(bcea_smoke, pos = "topright") plot(bcea_smoke, pos = "bottomleft") plot(bcea_smoke, pos = "bottomright") # ggplot2 plot(bcea_smoke, graph = "ggplot", pos = c(1,0)) plot(bcea_smoke, graph = "ggplot", pos = c(1,1)) plot(bcea_smoke, graph = "ggplot", pos = TRUE) plot(bcea_smoke, graph = "ggplot", pos = FALSE) plot(bcea_smoke, graph = "ggplot", pos = "top") plot(bcea_smoke, graph = "ggplot", pos = "bottom") plot(bcea_smoke, graph = "ggplot", pos = "left") plot(bcea_smoke, graph = "ggplot", pos = "right") ``` ```{r eval=FALSE, echo=FALSE} # create output docs rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "pdf_document", output_dir = "vignettes") rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "html_document", output_dir = "vignettes") ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/CEriskav.Rmd
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6, fig.height = 4 ) ## ----setup-------------------------------------------------------------------- library(BCEA) ## ----eval=FALSE--------------------------------------------------------------- # bcea(eff, cost, # ref = 1, # interventions = NULL, # .comparison = NULL, # Kmax = 50000, # wtp = NULL, # plot = FALSE) ## ----------------------------------------------------------------------------- data(Vaccine) ## ----------------------------------------------------------------------------- he_ref1 <- bcea(eff, cost, ref = 1, interventions = treats, Kmax = 50000) str(he_ref1) ceplane.plot(he_ref1) ## ----------------------------------------------------------------------------- he_ref2 <- bcea(eff, cost, ref = 2, interventions = treats, Kmax = 50000) str(he_ref2[c("n_comparators", "ICER", "ref", "comp")]) ## ----------------------------------------------------------------------------- setReferenceGroup(he_ref1) <- 2 str(he_ref1[c("n_comparators", "ICER", "ref", "comp")]) ## ----------------------------------------------------------------------------- he_Kmax1 <- bcea(eff, cost, ref = 1, interventions = treats, Kmax = 50000) str(he_Kmax1[c("n_comparators", "ICER", "ref", "comp", "Kmax")]) ## ----------------------------------------------------------------------------- he_Kmax2 <- bcea(eff, cost, ref = 2, interventions = treats, Kmax = 2000) str(he_Kmax2[c("n_comparators", "ICER", "ref", "comp", "Kmax")]) ## ----------------------------------------------------------------------------- setKmax(he_Kmax1) <- 2000 str(he_Kmax1[c("n_comparators", "ICER", "ref", "comp", "Kmax")]) ## ----------------------------------------------------------------------------- data(Smoking) ## ----------------------------------------------------------------------------- he_comp234 <- bcea(eff, cost, ref = 1, interventions = treats, Kmax = 50000) str(he_comp234[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp234, wtp = 2000) ## ----------------------------------------------------------------------------- he_comp2 <- bcea(eff, cost, ref = 1, .comparison = 2, interventions = treats, Kmax = 2000) str(he_comp2[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp2, wtp = 2000) ## ----------------------------------------------------------------------------- setComparisons(he_comp234) <- 2 str(he_comp234[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp234, wtp = 2000) ## ----------------------------------------------------------------------------- he_comp24 <- bcea(eff, cost, ref = 1, .comparison = c(2,4), interventions = treats, Kmax = 2000) str(he_comp24[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp24, wtp = 2000) ## ----------------------------------------------------------------------------- setComparisons(he_comp234) <- c(2,4) str(he_comp234[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp24, wtp = 2000) ## ----------------------------------------------------------------------------- ceplane.plot(he_comp234, comparison = 2, wtp = 2000) ceplane.plot(he_comp234, comparison = c(2,4), wtp = 2000) ## ----echo=FALSE--------------------------------------------------------------- # create output docs # rmarkdown::render(input = "vignettes/Set_bcea_parameters.Rmd", output_format = "pdf_document", output_dir = "vignettes") # rmarkdown::render(input = "vignettes/Set_bcea_parameters.Rmd", output_format = "html_document", output_dir = "vignettes")
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/Set_bcea_parameters.R
--- title: "Set bcea() Parameters: Constructor and Setters" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Set bcea() Parameters: Constructor and Setters} %\VignetteEngine{knitr::knitr} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6, fig.height = 4 ) ``` ```{r setup} library(BCEA) ``` There are several arguments passed to `bcea()` to specify the form of the analysis. These are ```{r eval=FALSE} bcea(eff, cost, ref = 1, interventions = NULL, .comparison = NULL, Kmax = 50000, wtp = NULL, plot = FALSE) ``` Those of interest here are: * `ref` is the reference intervention group to compare against the other groups. * `.comparisons` are the groups to compare against `ref`. The default is all of the non-`ref` groups. This is a new argument in the latest release of BCEA to make it more flexible and consistent with other functions. A preceding dot is used to keep it back-compatible with previous versions of BCEA. Argument `c` is partially matched with both `c` and `comparison` otherwise throwing an error. * `Kmax` is the maximum value of the willingness-to-pay to calculate statistics for. During an analysis we may want to explore changing some of these parameters and keeping all of the others the same. We can do with with package setter functions. ### Changing Reference Group Load cost-effectiveness data. ```{r} data(Vaccine) ``` We first create `bcea` object using the constructor function for 2 different reference groups. ```{r} he_ref1 <- bcea(eff, cost, ref = 1, interventions = treats, Kmax = 50000) str(he_ref1) ceplane.plot(he_ref1) ``` ```{r} he_ref2 <- bcea(eff, cost, ref = 2, interventions = treats, Kmax = 50000) str(he_ref2[c("n_comparators", "ICER", "ref", "comp")]) ``` Alternatively, we can do the same by modifying the first output. ```{r} setReferenceGroup(he_ref1) <- 2 str(he_ref1[c("n_comparators", "ICER", "ref", "comp")]) ``` ### Changing Kmax In the same way as above we can change `Kmax` in 2 equivalent ways. ```{r} he_Kmax1 <- bcea(eff, cost, ref = 1, interventions = treats, Kmax = 50000) str(he_Kmax1[c("n_comparators", "ICER", "ref", "comp", "Kmax")]) ``` ```{r} he_Kmax2 <- bcea(eff, cost, ref = 2, interventions = treats, Kmax = 2000) str(he_Kmax2[c("n_comparators", "ICER", "ref", "comp", "Kmax")]) ``` ```{r} setKmax(he_Kmax1) <- 2000 str(he_Kmax1[c("n_comparators", "ICER", "ref", "comp", "Kmax")]) ``` ### Change Comparison Groups Lets load some data with more than two groups. ```{r} data(Smoking) ``` Defaults is all other groups which in this case is 2, 3 and 4. ```{r} he_comp234 <- bcea(eff, cost, ref = 1, interventions = treats, Kmax = 50000) str(he_comp234[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp234, wtp = 2000) ``` Let us compare against only groups 2. ```{r} he_comp2 <- bcea(eff, cost, ref = 1, .comparison = 2, interventions = treats, Kmax = 2000) str(he_comp2[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp2, wtp = 2000) ``` We can achieve the same thing using the appropriate setter. ```{r} setComparisons(he_comp234) <- 2 str(he_comp234[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp234, wtp = 2000) ``` We can select multiple comparison groups too. Let us compare against only groups 2 and 4. ```{r} he_comp24 <- bcea(eff, cost, ref = 1, .comparison = c(2,4), interventions = treats, Kmax = 2000) str(he_comp24[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp24, wtp = 2000) ``` ```{r} setComparisons(he_comp234) <- c(2,4) str(he_comp234[c("n_comparators", "ICER", "ref", "comp")]) ceplane.plot(he_comp24, wtp = 2000) ``` Further, a `bcea` object with all comparison groups can be passed to other functions such as `ceplane.plot` and `ceac.plot` with a `comparison` argument, which will do the modifications using these functions internally instead. ```{r} ceplane.plot(he_comp234, comparison = 2, wtp = 2000) ceplane.plot(he_comp234, comparison = c(2,4), wtp = 2000) ``` ```{r echo=FALSE} # create output docs # rmarkdown::render(input = "vignettes/Set_bcea_parameters.Rmd", output_format = "pdf_document", output_dir = "vignettes") # rmarkdown::render(input = "vignettes/Set_bcea_parameters.Rmd", output_format = "html_document", output_dir = "vignettes") ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/Set_bcea_parameters.Rmd
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup, warning=FALSE, message=FALSE-------------------------------------- library(BCEA) ## ----------------------------------------------------------------------------- data(Smoking) ## ----------------------------------------------------------------------------- treats <- c("No intervention", "Self-help", "Individual counselling", "Group counselling") ## ----------------------------------------------------------------------------- bcea_smoke <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) ## ----fig.width=10, fig.height=10---------------------------------------------- library(ggplot2) library(purrr) plot(bcea_smoke) ## ----------------------------------------------------------------------------- ceplane.plot(bcea_smoke, comparison = 2, wtp = 250) eib.plot(bcea_smoke) contour(bcea_smoke) ceac.plot(bcea_smoke) ib.plot(bcea_smoke) ## ----------------------------------------------------------------------------- plot(bcea_smoke, graph = "ggplot2", wtp = 250, line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5))
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/bcea.R
--- title: "Getting Started" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Getting Started} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This vignette will demonstrate a simple cost-effectiveness analysis using __BCEA__ using the smoking cessation data set contained in the package. ```{r setup, warning=FALSE, message=FALSE} library(BCEA) ``` Load the data. ```{r} data(Smoking) ``` This study has four interventions. ```{r} treats <- c("No intervention", "Self-help", "Individual counselling", "Group counselling") ``` Setting the reference group (`ref`) to _Group counselling_ and the maximum willingness to pay (`Kmax`) as 500. ```{r} bcea_smoke <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) ``` We can easily create a grid of the most common plots ```{r fig.width=10, fig.height=10} library(ggplot2) library(purrr) plot(bcea_smoke) ``` Individual plots can be plotting using their own functions. ```{r} ceplane.plot(bcea_smoke, comparison = 2, wtp = 250) eib.plot(bcea_smoke) contour(bcea_smoke) ceac.plot(bcea_smoke) ib.plot(bcea_smoke) ``` More on this in the other vignettes but you can change the default plotting style, such as follows. ```{r} plot(bcea_smoke, graph = "ggplot2", wtp = 250, line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5)) ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/bcea.Rmd
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ## ----setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE---------- library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ## ----------------------------------------------------------------------------- data("Vaccine") he <- bcea(eff, cost) # str(he) ceac.plot(he) ## ----------------------------------------------------------------------------- ceac.plot(he, graph = "base") ceac.plot(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ## ----------------------------------------------------------------------------- ceac.plot(he, graph = "ggplot2", title = "my title", line = list(color = "green"), theme = theme_dark()) ## ----------------------------------------------------------------------------- data("Smoking") he <- bcea(eff, cost, ref = 4) # str(he) ## ----------------------------------------------------------------------------- ceac.plot(he) ceac.plot(he, graph = "base", title = "my title", line = list(color = "green")) ## ----------------------------------------------------------------------------- ceac.plot(he, graph = "ggplot2", title = "my title", line = list(color = "green")) ## ----------------------------------------------------------------------------- ceac.plot(he, pos = FALSE) # bottom right ceac.plot(he, pos = c(0, 0)) ceac.plot(he, pos = c(0, 1)) ceac.plot(he, pos = c(1, 0)) ceac.plot(he, pos = c(1, 1)) ## ----------------------------------------------------------------------------- ceac.plot(he, graph = "ggplot2", pos = c(0, 0)) ceac.plot(he, graph = "ggplot2", pos = c(0, 1)) ceac.plot(he, graph = "ggplot2", pos = c(1, 0)) ceac.plot(he, graph = "ggplot2", pos = c(1, 1)) ## ----------------------------------------------------------------------------- mypalette <- RColorBrewer::brewer.pal(3, "Accent") ceac.plot(he, graph = "base", title = "my title", line = list(color = mypalette), pos = FALSE) ceac.plot(he, graph = "ggplot2", title = "my title", line = list(color = mypalette), pos = FALSE) ## ----------------------------------------------------------------------------- he <- multi.ce(he) ## ----------------------------------------------------------------------------- ceac.plot(he, graph = "base") ceac.plot(he, graph = "base", title = "my title", line = list(color = "green"), pos = FALSE) mypalette <- RColorBrewer::brewer.pal(4, "Dark2") ceac.plot(he, graph = "base", title = "my title", line = list(color = mypalette), pos = c(0,1)) ## ----------------------------------------------------------------------------- ceac.plot(he, graph = "ggplot2", title = "my title", line = list(color = mypalette), pos = c(0,1)) ## ----------------------------------------------------------------------------- ceac.plot(he, graph = "ggplot2", title = "my title", line = list(size = 2)) ## ----------------------------------------------------------------------------- ceac.plot(he, graph = "ggplot2", title = "my title", line = list(size = c(1,2,3))) ## ----echo=FALSE--------------------------------------------------------------- # create output docs # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "pdf_document", output_dir = "vignettes") # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "html_document", output_dir = "vignettes")
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/ceac.R
--- title: "Cost-Effectiveness Acceptability Curve Plots" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Cost-Effectiveness Acceptability Curve Plots} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ``` ```{r setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE} library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ``` ## Introduction The intention of this vignette is to show how to plot different styles of cost-effectiveness acceptability curves using the BCEA package. ## Two interventions only This is the simplest case, usually an alternative intervention ($i=1$) versus status-quo ($i=0$). The plot show the probability that the alternative intervention is cost-effective for each willingness to pay, $k$, $$ p(NB_1 \geq NB_0 | k) \mbox{ where } NB_i = ke - c $$ Using the set of $N$ posterior samples, this is approximated by $$ \frac{1}{N} \sum_j^N \mathbb{I} (k \Delta e^j - \Delta c^j) $$ #### R code To calculate these in BCEA we use the `bcea()` function. ```{r} data("Vaccine") he <- bcea(eff, cost) # str(he) ceac.plot(he) ``` The plot defaults to base R plotting. Type of plot can be set explicitly using the `graph` argument. ```{r} ceac.plot(he, graph = "base") ceac.plot(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ``` Other plotting arguments can be specified such as title, line colours and theme. ```{r} ceac.plot(he, graph = "ggplot2", title = "my title", line = list(color = "green"), theme = theme_dark()) ``` ## Multiple interventions This situation is when there are more than two interventions to consider. Incremental values can be obtained either always against a fixed reference intervention, such as status-quo, or for all pair-wise comparisons. ### Against a fixed reference intervention Without loss of generality, if we assume that we are interested in intervention $i=1$, then we wish to calculate $$ p(NB_1 \geq NB_s | k) \;\; \exists \; s \in S $$ Using the set of $N$ posterior samples, this is approximated by $$ \frac{1}{N} \sum_j^N \mathbb{I} (k \Delta e_{1,s}^j - \Delta c_{1,s}^j) $$ #### R code This is the default plot for `ceac.plot()` so we simply follow the same steps as above with the new data set. ```{r} data("Smoking") he <- bcea(eff, cost, ref = 4) # str(he) ``` ```{r} ceac.plot(he) ceac.plot(he, graph = "base", title = "my title", line = list(color = "green")) ``` ```{r} ceac.plot(he, graph = "ggplot2", title = "my title", line = list(color = "green")) ``` Reposition legend. ```{r} ceac.plot(he, pos = FALSE) # bottom right ceac.plot(he, pos = c(0, 0)) ceac.plot(he, pos = c(0, 1)) ceac.plot(he, pos = c(1, 0)) ceac.plot(he, pos = c(1, 1)) ``` ```{r} ceac.plot(he, graph = "ggplot2", pos = c(0, 0)) ceac.plot(he, graph = "ggplot2", pos = c(0, 1)) ceac.plot(he, graph = "ggplot2", pos = c(1, 0)) ceac.plot(he, graph = "ggplot2", pos = c(1, 1)) ``` Define colour palette. ```{r} mypalette <- RColorBrewer::brewer.pal(3, "Accent") ceac.plot(he, graph = "base", title = "my title", line = list(color = mypalette), pos = FALSE) ceac.plot(he, graph = "ggplot2", title = "my title", line = list(color = mypalette), pos = FALSE) ``` ### Pair-wise comparisons Again, without loss of generality, if we assume that we are interested in intervention $i=1$, then we wish to calculate $$ p(NB_1 = \max\{NB_i : i \in S\} | k) $$ This can be approximated by the following. $$ \frac{1}{N} \sum_j^N \prod_{i \in S} \mathbb{I} (k \Delta e_{1,i}^j - \Delta c_{1,i}^j) $$ #### R code In BCEA we first we must determine all combinations of paired interventions using the `multi.ce()` function. ```{r} he <- multi.ce(he) ``` We can use the same plotting calls as before i.e. `ceac.plot()` and BCEA will deal with the pairwise situation appropriately. Note that in this case the probabilities at a given willingness to pay sum to 1. ```{r} ceac.plot(he, graph = "base") ceac.plot(he, graph = "base", title = "my title", line = list(color = "green"), pos = FALSE) mypalette <- RColorBrewer::brewer.pal(4, "Dark2") ceac.plot(he, graph = "base", title = "my title", line = list(color = mypalette), pos = c(0,1)) ``` ```{r} ceac.plot(he, graph = "ggplot2", title = "my title", line = list(color = mypalette), pos = c(0,1)) ``` The line width can be changes with either a single value to change all lines to the same thickness or a value for each. ```{r} ceac.plot(he, graph = "ggplot2", title = "my title", line = list(size = 2)) ``` ```{r} ceac.plot(he, graph = "ggplot2", title = "my title", line = list(size = c(1,2,3))) ``` ```{r echo=FALSE} # create output docs # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "pdf_document", output_dir = "vignettes") # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "html_document", output_dir = "vignettes") ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/ceac.Rmd
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ## ----setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE---------- library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ## ----------------------------------------------------------------------------- data(Smoking) treats <- c("No intervention", "Self-help", "Individual counselling", "Group counselling") bcea_smoke <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) ## ----------------------------------------------------------------------------- # all interventions ceef.plot(bcea_smoke) # subset setComparisons(bcea_smoke) <- c(1,3) ceef.plot(bcea_smoke) # check numbering and legend setComparisons(bcea_smoke) <- c(3,1) ceef.plot(bcea_smoke) setComparisons(bcea_smoke) <- c(3,2) ceef.plot(bcea_smoke) setComparisons(bcea_smoke) <- 1 ceef.plot(bcea_smoke) # add interventions back in setComparisons(bcea_smoke) <- c(1,3) ceef.plot(bcea_smoke) ## ----error=TRUE--------------------------------------------------------------- bcea_smoke <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) # all interventions ceef.plot(bcea_smoke, graph = "ggplot") # subset setComparisons(bcea_smoke) <- c(1,3) ceef.plot(bcea_smoke, graph = "ggplot") # check numbering and legend setComparisons(bcea_smoke) <- c(3,1) ceef.plot(bcea_smoke, graph = "ggplot") setComparisons(bcea_smoke) <- c(3,2) ceef.plot(bcea_smoke, graph = "ggplot") setComparisons(bcea_smoke) <- 1 ceef.plot(bcea_smoke, graph = "ggplot") # add interventions back in setComparisons(bcea_smoke) <- c(1,3) ceef.plot(bcea_smoke, graph = "ggplot") ## ----error=TRUE--------------------------------------------------------------- # base R ceef.plot(bcea_smoke, pos = c(1,0)) ceef.plot(bcea_smoke, pos = c(1,1)) ceef.plot(bcea_smoke, pos = TRUE) ceef.plot(bcea_smoke, pos = FALSE) ceef.plot(bcea_smoke, pos = "topleft") ceef.plot(bcea_smoke, pos = "topright") ceef.plot(bcea_smoke, pos = "bottomleft") ceef.plot(bcea_smoke, pos = "bottomright") # ggplot2 ceef.plot(bcea_smoke, graph = "ggplot", pos = c(1,0)) ceef.plot(bcea_smoke, graph = "ggplot", pos = c(1,1)) ceef.plot(bcea_smoke, graph = "ggplot", pos = TRUE) ceef.plot(bcea_smoke, graph = "ggplot", pos = FALSE) ceef.plot(bcea_smoke, graph = "ggplot", pos = "top") ceef.plot(bcea_smoke, graph = "ggplot", pos = "bottom") ceef.plot(bcea_smoke, graph = "ggplot", pos = "left") ceef.plot(bcea_smoke, graph = "ggplot", pos = "right") ## ----error=TRUE--------------------------------------------------------------- ceef.plot(bcea_smoke, flip = TRUE, dominance = FALSE, start.from.origins = FALSE, print.summary = FALSE, graph = "base") ceef.plot(bcea_smoke, dominance = TRUE, start.from.origins = FALSE, pos = TRUE, print.summary = FALSE, graph = "ggplot2") ## ----error=TRUE--------------------------------------------------------------- ceef.plot(bcea_smoke, flip = TRUE, dominance = TRUE, start.from.origins = TRUE, print.summary = FALSE, graph = "base") ceef.plot(bcea_smoke, dominance = TRUE, start.from.origins = TRUE, pos = TRUE, print.summary = FALSE, graph = "ggplot2") ## ----error=TRUE--------------------------------------------------------------- data("Smoking") cost[, 4] <- -cost[, 4] bcea_smoke <- bcea(eff, cost, ref = 3, interventions = treats, Kmax = 500) # all interventions ceef.plot(bcea_smoke, graph = "ggplot") ceef.plot(bcea_smoke, graph = "base") ceef.plot(bcea_smoke, start.from.origins = TRUE, graph = "ggplot") ceef.plot(bcea_smoke, start.from.origins = TRUE, graph = "base") setComparisons(bcea_smoke) <- c(1,2) ceef.plot(bcea_smoke, graph = "ggplot") ceef.plot(bcea_smoke, graph = "base") eff[, 3] <- -eff[, 3] bcea_smoke <- bcea(eff, cost, ref = 3, interventions = treats, Kmax = 500) ceef.plot(bcea_smoke, graph = "ggplot") ceef.plot(bcea_smoke, graph = "base") data("Smoking") eff[, 3] <- -eff[, 3] bcea_smoke <- bcea(eff, cost, ref = 3, interventions = treats, Kmax = 500) ceef.plot(bcea_smoke, graph = "ggplot") ceef.plot(bcea_smoke, graph = "base") ## ----eval=FALSE, echo=FALSE--------------------------------------------------- # # create output docs # rmarkdown::render(input = "vignettes/ceef.Rmd", output_format = "pdf_document", output_dir = "vignettes") # rmarkdown::render(input = "vignettes/ceef.Rmd", output_format = "html_document", output_dir = "vignettes")
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/ceef.R
--- title: "Cost-Effectiveness Efficiency Frontier" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Cost-Effectiveness Efficiency Frontier} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ``` ```{r setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE} library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ``` ## Introduction The line connecting successive points on a cost-effectiveness plane which each represent the effect and cost associated with different treatment alternatives. The gradient of a line segment represents the ICER of the treatment comparison between the two alternatives represented by that segment. The cost-effectiveness frontier consists of the set of points corresponding to treatment alternatives that are considered to be cost-effective at different values of the cost-effectiveness threshold. The steeper the gradient between successive points on the frontier, the higher is the ICER between these treatment alternatives and the more expensive alternative would be considered cost-effective only when a high value of the cost-effectiveness threshold is assumed. Points not lying on the cost-effectiveness frontier represent treatment alternatives that are not considered cost-effective at any value of the cost-effectiveness threshold. ## R code To create the plots in BCEA we first call the `bcea()` function. ```{r} data(Smoking) treats <- c("No intervention", "Self-help", "Individual counselling", "Group counselling") bcea_smoke <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) ``` * base R ```{r} # all interventions ceef.plot(bcea_smoke) # subset setComparisons(bcea_smoke) <- c(1,3) ceef.plot(bcea_smoke) # check numbering and legend setComparisons(bcea_smoke) <- c(3,1) ceef.plot(bcea_smoke) setComparisons(bcea_smoke) <- c(3,2) ceef.plot(bcea_smoke) setComparisons(bcea_smoke) <- 1 ceef.plot(bcea_smoke) # add interventions back in setComparisons(bcea_smoke) <- c(1,3) ceef.plot(bcea_smoke) ``` * ggplot ```{r error=TRUE} bcea_smoke <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) # all interventions ceef.plot(bcea_smoke, graph = "ggplot") # subset setComparisons(bcea_smoke) <- c(1,3) ceef.plot(bcea_smoke, graph = "ggplot") # check numbering and legend setComparisons(bcea_smoke) <- c(3,1) ceef.plot(bcea_smoke, graph = "ggplot") setComparisons(bcea_smoke) <- c(3,2) ceef.plot(bcea_smoke, graph = "ggplot") setComparisons(bcea_smoke) <- 1 ceef.plot(bcea_smoke, graph = "ggplot") # add interventions back in setComparisons(bcea_smoke) <- c(1,3) ceef.plot(bcea_smoke, graph = "ggplot") ``` Check legend position argument: ```{r error=TRUE} # base R ceef.plot(bcea_smoke, pos = c(1,0)) ceef.plot(bcea_smoke, pos = c(1,1)) ceef.plot(bcea_smoke, pos = TRUE) ceef.plot(bcea_smoke, pos = FALSE) ceef.plot(bcea_smoke, pos = "topleft") ceef.plot(bcea_smoke, pos = "topright") ceef.plot(bcea_smoke, pos = "bottomleft") ceef.plot(bcea_smoke, pos = "bottomright") # ggplot2 ceef.plot(bcea_smoke, graph = "ggplot", pos = c(1,0)) ceef.plot(bcea_smoke, graph = "ggplot", pos = c(1,1)) ceef.plot(bcea_smoke, graph = "ggplot", pos = TRUE) ceef.plot(bcea_smoke, graph = "ggplot", pos = FALSE) ceef.plot(bcea_smoke, graph = "ggplot", pos = "top") ceef.plot(bcea_smoke, graph = "ggplot", pos = "bottom") ceef.plot(bcea_smoke, graph = "ggplot", pos = "left") ceef.plot(bcea_smoke, graph = "ggplot", pos = "right") ``` ### Flipping plot ```{r error=TRUE} ceef.plot(bcea_smoke, flip = TRUE, dominance = FALSE, start.from.origins = FALSE, print.summary = FALSE, graph = "base") ceef.plot(bcea_smoke, dominance = TRUE, start.from.origins = FALSE, pos = TRUE, print.summary = FALSE, graph = "ggplot2") ``` ### Start from origin or smallest (e,c). ```{r error=TRUE} ceef.plot(bcea_smoke, flip = TRUE, dominance = TRUE, start.from.origins = TRUE, print.summary = FALSE, graph = "base") ceef.plot(bcea_smoke, dominance = TRUE, start.from.origins = TRUE, pos = TRUE, print.summary = FALSE, graph = "ggplot2") ``` ### Negative cost or effectiveness ```{r error=TRUE} data("Smoking") cost[, 4] <- -cost[, 4] bcea_smoke <- bcea(eff, cost, ref = 3, interventions = treats, Kmax = 500) # all interventions ceef.plot(bcea_smoke, graph = "ggplot") ceef.plot(bcea_smoke, graph = "base") ceef.plot(bcea_smoke, start.from.origins = TRUE, graph = "ggplot") ceef.plot(bcea_smoke, start.from.origins = TRUE, graph = "base") setComparisons(bcea_smoke) <- c(1,2) ceef.plot(bcea_smoke, graph = "ggplot") ceef.plot(bcea_smoke, graph = "base") eff[, 3] <- -eff[, 3] bcea_smoke <- bcea(eff, cost, ref = 3, interventions = treats, Kmax = 500) ceef.plot(bcea_smoke, graph = "ggplot") ceef.plot(bcea_smoke, graph = "base") data("Smoking") eff[, 3] <- -eff[, 3] bcea_smoke <- bcea(eff, cost, ref = 3, interventions = treats, Kmax = 500) ceef.plot(bcea_smoke, graph = "ggplot") ceef.plot(bcea_smoke, graph = "base") ``` ```{r eval=FALSE, echo=FALSE} # create output docs rmarkdown::render(input = "vignettes/ceef.Rmd", output_format = "pdf_document", output_dir = "vignettes") rmarkdown::render(input = "vignettes/ceef.Rmd", output_format = "html_document", output_dir = "vignettes") ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/ceef.Rmd
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ## ----setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE---------- library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ## ----------------------------------------------------------------------------- data("Vaccine") he <- bcea(eff, cost) ## ----------------------------------------------------------------------------- ceplane.plot(he, graph = "base") ceplane.plot(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ## ----------------------------------------------------------------------------- ceplane.plot(he, graph = "ggplot2", title = "my title", line = list(color = "green", size = 3), point = list(color = "blue", shape = 10, size = 5), icer = list(color = "orange", size = 5), area = list(fill = "grey"), theme = theme_linedraw()) ## ----------------------------------------------------------------------------- ceplane.plot(he, graph = "ggplot2", point = list(size = NA), icer = list(size = 5)) ## ----------------------------------------------------------------------------- data("Smoking") he <- bcea(eff, cost, ref = 4) # str(he) ## ----------------------------------------------------------------------------- ceplane.plot(he) ceplane.plot(he, graph = "ggplot2") ## ----------------------------------------------------------------------------- ceplane.plot(he, graph = "ggplot2", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5)) ## ----------------------------------------------------------------------------- ceplane.plot(he, pos = FALSE) # bottom right ceplane.plot(he, pos = c(0, 0)) ceplane.plot(he, pos = c(0, 1)) ceplane.plot(he, pos = c(1, 0)) ceplane.plot(he, pos = c(1, 1))
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/ceplane.R
--- title: "Cost-effectiveness plane" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Cost-effectiveness plane} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ``` ```{r setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE} library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ``` ##TODO... ## Introduction The intention of this vignette is to show how to plot different styles of cost-effectiveness acceptability curves using the BCEA package. #### R code To calculate these in BCEA we use the `bcea()` function. ```{r} data("Vaccine") he <- bcea(eff, cost) ``` The plot defaults to base R plotting. Type of plot can be set explicitly using the `graph` argument. ```{r} ceplane.plot(he, graph = "base") ceplane.plot(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ``` Other plotting arguments can be specified such as title, line colours and theme. ```{r} ceplane.plot(he, graph = "ggplot2", title = "my title", line = list(color = "green", size = 3), point = list(color = "blue", shape = 10, size = 5), icer = list(color = "orange", size = 5), area = list(fill = "grey"), theme = theme_linedraw()) ``` If you only what the mean point then you can suppress the sample points by passing size `NA`. ```{r} ceplane.plot(he, graph = "ggplot2", point = list(size = NA), icer = list(size = 5)) ``` ## Multiple interventions This situation is when there are more than two interventions to consider. #### R code ```{r} data("Smoking") he <- bcea(eff, cost, ref = 4) # str(he) ``` ```{r} ceplane.plot(he) ceplane.plot(he, graph = "ggplot2") ``` ```{r} ceplane.plot(he, graph = "ggplot2", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5)) ``` Reposition legend. ```{r} ceplane.plot(he, pos = FALSE) # bottom right ceplane.plot(he, pos = c(0, 0)) ceplane.plot(he, pos = c(0, 1)) ceplane.plot(he, pos = c(1, 0)) ceplane.plot(he, pos = c(1, 1)) ``` <!-- ```{r} --> <!-- ceac.plot(he, graph = "ggplot2", pos = c(0, 0)) --> <!-- ceac.plot(he, graph = "ggplot2", pos = c(0, 1)) --> <!-- ceac.plot(he, graph = "ggplot2", pos = c(1, 0)) --> <!-- ceac.plot(he, graph = "ggplot2", pos = c(1, 1)) --> <!-- ``` --> <!-- Define colour palette. --> <!-- ```{r} --> <!-- mypalette <- RColorBrewer::brewer.pal(3, "Accent") --> <!-- ceac.plot(he, --> <!-- graph = "base", --> <!-- title = "my title", --> <!-- line = list(colors = mypalette), --> <!-- pos = FALSE) --> <!-- ceac.plot(he, --> <!-- graph = "ggplot2", --> <!-- title = "my title", --> <!-- line = list(colors = mypalette), --> <!-- pos = FALSE) --> <!-- ``` --> <!-- ### Pair-wise comparisons --> <!-- Again, without loss of generality, if we assume that we are interested in intervention $i=1$, the we wish to calculate --> <!-- $$ --> <!-- p(NB_1 = \max\{NB_i : i \in S\} | k) --> <!-- $$ --> <!-- This can be approximated by the following. --> <!-- $$ --> <!-- \frac{1}{N} \sum_j^N \prod_{i \in S} \mathbb{I} (k \Delta e_{1,i}^j - \Delta c_{1,i}^j) --> <!-- $$ --> <!-- #### R code --> <!-- In BCEA we first we must determine all combinations of paired interventions using the `multi.ce()` function. --> <!-- ```{r} --> <!-- he <- multi.ce(he) --> <!-- ``` --> <!-- We can use the same plotting calls as before i.e. `ceac.plot()` and BCEA will deal with the pairwise situation appropriately. --> <!-- Note that in this case the probabilities at a given willingness to pay sum to 1. --> <!-- ```{r} --> <!-- ceac.plot(he, graph = "base") --> <!-- ceac.plot(he, --> <!-- graph = "base", --> <!-- title = "my title", --> <!-- line = list(colors = "green"), --> <!-- pos = FALSE) --> <!-- mypalette <- RColorBrewer::brewer.pal(4, "Dark2") --> <!-- ceac.plot(he, --> <!-- graph = "base", --> <!-- title = "my title", --> <!-- line = list(colors = mypalette), --> <!-- pos = c(0,1)) --> <!-- ``` --> <!-- ```{r} --> <!-- ceac.plot(he, --> <!-- graph = "ggplot2", --> <!-- title = "my title", --> <!-- line = list(colors = mypalette), --> <!-- pos = c(0,1)) --> <!-- ``` --> <!-- ```{r echo=FALSE} --> <!-- # create output docs --> <!-- # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "pdf_document", output_dir = "vignettes") --> <!-- # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "html_document", output_dir = "vignettes") --> <!-- ``` -->
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/ceplane.Rmd
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ## ----setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE---------- library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ## ----------------------------------------------------------------------------- data("Vaccine") he <- bcea(eff, cost, ref = 2) ## ----------------------------------------------------------------------------- contour(he, graph = "base") contour(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ## ----------------------------------------------------------------------------- contour(he, levels = c(0.2, 0.8)) contour(he, graph = "ggplot2", contour = list(breaks = c(0.2, 0.8))) ## ----------------------------------------------------------------------------- contour(he, graph = "ggplot2", title = "my title", point = list(color = "blue", shape = 2, size = 5), contour = list(size = 2)) ## ----------------------------------------------------------------------------- contour(he, graph = "base", title = "my title", point = list(color = "blue", shape = 2, size = 2), contour = list(size = 2)) ## ----------------------------------------------------------------------------- contour2(he, graph = "base") contour2(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ## ----------------------------------------------------------------------------- contour2(he, graph = "ggplot2", title = "my title", point = list(color = "blue", shape = 10, size = 5), contour = list(size = 2)) ## ----------------------------------------------------------------------------- contour2(he, graph = "base", title = "my title", point = list(color = "blue", shape = 2, size = 3), contour = list(size = 4)) ## ----------------------------------------------------------------------------- data("Smoking") he <- bcea(eff, cost, ref = 4) # str(he) ## ----------------------------------------------------------------------------- contour(he) contour(he, graph = "ggplot2") ## ----------------------------------------------------------------------------- contour(he, scale = 0.9) contour(he, graph = "ggplot2", scale = 0.9) ##TODO: what is the equivalent ggplot2 argument? ## ----------------------------------------------------------------------------- contour(he, nlevels = 10) contour(he, graph = "ggplot2", contour = list(bins = 10)) ## ----------------------------------------------------------------------------- contour(he, levels = c(0.2, 0.8)) contour(he, graph = "ggplot2", contour = list(breaks = c(0.2, 0.8))) ## ----------------------------------------------------------------------------- contour(he, graph = "ggplot2", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5), contour = list(size = 2)) ## ----------------------------------------------------------------------------- contour(he, graph = "base", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5), contour = list(size = 4)) ## ----------------------------------------------------------------------------- contour2(he, wtp = 250) contour2(he, wtp = 250, graph = "ggplot2") ## ----------------------------------------------------------------------------- contour2(he, wtp = 250, graph = "ggplot2", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5), contour = list(size = 2)) ## ----------------------------------------------------------------------------- contour2(he, wtp = 250, graph = "base", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5), contour = list(size = 4)) ## ----------------------------------------------------------------------------- contour(he, pos = FALSE) # bottom right contour(he, pos = c(0, 0)) contour(he, pos = c(0, 1)) contour(he, pos = c(1, 0)) contour(he, pos = c(1, 1))
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/contour.R
--- title: "Contour Plots" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Contour Plots} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ``` ```{r setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE} library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ``` ## Introduction The intention of this vignette is to show how to plot different styles of contour plot using the BCEA package and the `contour()` and `contour2()` functions. #### R code To calculate these in BCEA we use the `bcea()` function. ```{r} data("Vaccine") he <- bcea(eff, cost, ref = 2) ``` The plot defaults to base R plotting. Type of plot can be set explicitly using the `graph` argument. ```{r} contour(he, graph = "base") contour(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ``` User-defined contour levels can be provided. The `levels` and `nlevels` arguments specify the quantiles or number of levels. The base R levels arguments are kept for back-compatibility and the `ggplot2` style arguments are used in the associated plot. ```{r} contour(he, levels = c(0.2, 0.8)) contour(he, graph = "ggplot2", contour = list(breaks = c(0.2, 0.8))) ``` Other plotting arguments can be specified such as title, line colour and thickness and type of point. ```{r} contour(he, graph = "ggplot2", title = "my title", point = list(color = "blue", shape = 2, size = 5), contour = list(size = 2)) ``` ```{r} contour(he, graph = "base", title = "my title", point = list(color = "blue", shape = 2, size = 2), contour = list(size = 2)) ``` Alternatively, the `contour2()` function is essentially a wrapper for `ceplane.plot()` with the addition of contour lines. ```{r} contour2(he, graph = "base") contour2(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ``` Other plotting arguments can be specified in exactly the same way as above. ```{r} contour2(he, graph = "ggplot2", title = "my title", point = list(color = "blue", shape = 10, size = 5), contour = list(size = 2)) ``` ```{r} contour2(he, graph = "base", title = "my title", point = list(color = "blue", shape = 2, size = 3), contour = list(size = 4)) ``` ## Multiple interventions This situation is when there are more than two interventions to consider. #### R code ```{r} data("Smoking") he <- bcea(eff, cost, ref = 4) # str(he) ``` Because there are multiple groups then the quadrant annotation is omitted. ```{r} contour(he) contour(he, graph = "ggplot2") ``` The `scale` argument determines the smoothness of the contours. ```{r} contour(he, scale = 0.9) contour(he, graph = "ggplot2", scale = 0.9) ##TODO: what is the equivalent ggplot2 argument? ``` The quantiles or number of levels. ```{r} contour(he, nlevels = 10) contour(he, graph = "ggplot2", contour = list(bins = 10)) ``` ```{r} contour(he, levels = c(0.2, 0.8)) contour(he, graph = "ggplot2", contour = list(breaks = c(0.2, 0.8))) ``` ```{r} contour(he, graph = "ggplot2", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5), contour = list(size = 2)) ``` ```{r} contour(he, graph = "base", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5), contour = list(size = 4)) ``` Again, this applies to the `contour2()` version of contour plot too. ```{r} contour2(he, wtp = 250) contour2(he, wtp = 250, graph = "ggplot2") ``` The styling of the plot for multiple comparisons can specifically change the colour and point type for each comparison. ```{r} contour2(he, wtp = 250, graph = "ggplot2", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5), contour = list(size = 2)) ``` ```{r} contour2(he, wtp = 250, graph = "base", title = "my title", line = list(color = "red", size = 1), point = list(color = c("plum", "tomato", "springgreen"), shape = 3:5, size = 2), icer = list(color = c("red", "orange", "black"), size = 5), contour = list(size = 4)) ``` Reposition legend. ```{r} contour(he, pos = FALSE) # bottom right contour(he, pos = c(0, 0)) contour(he, pos = c(0, 1)) contour(he, pos = c(1, 0)) contour(he, pos = c(1, 1)) ``` <!-- ```{r echo=FALSE} --> <!-- # create output docs --> <!-- # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "pdf_document", output_dir = "vignettes") --> <!-- # rmarkdown::render(input = "vignettes/ceac.Rmd", output_format = "html_document", output_dir = "vignettes") --> <!-- ``` -->
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/contour.Rmd
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6, fig.height = 6 ) ## ----setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE---------- library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ## ----------------------------------------------------------------------------- data(Vaccine) he <- bcea(eff, cost, ref = 2, interventions = treats, Kmax = 50000, plot = FALSE) ## ----------------------------------------------------------------------------- eib.plot(he) ## ----------------------------------------------------------------------------- eib.plot(he, graph = "base") eib.plot(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ## ----------------------------------------------------------------------------- eib.plot(he, graph = "ggplot2", main = "my title", line = list(color = "green"), theme = theme_dark()) ## ----------------------------------------------------------------------------- eib.plot(he, plot.cri = FALSE) ## ----------------------------------------------------------------------------- data(Smoking) treats <- c("No intervention", "Self-help", "Individual counselling", "Group counselling") he <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) eib.plot(he) ## ----------------------------------------------------------------------------- eib.plot(he, graph = "base", main = "my title", line = list(color = "green")) ## ----------------------------------------------------------------------------- eib.plot(he, graph = "ggplot2", main = "my title", line = list(color = "green")) ## ----------------------------------------------------------------------------- eib.plot(he, plot.cri = TRUE) ## ----------------------------------------------------------------------------- eib.plot(he, pos = FALSE) # bottom right eib.plot(he, pos = c(0, 0)) eib.plot(he, pos = c(0, 1)) eib.plot(he, pos = c(1, 0)) eib.plot(he, pos = c(1, 1)) ## ----------------------------------------------------------------------------- ##TODO: eib.plot(he, graph = "ggplot2", pos = c(0, 0)) eib.plot(he, graph = "ggplot2", pos = c(0, 1)) eib.plot(he, graph = "ggplot2", pos = c(1, 0)) eib.plot(he, graph = "ggplot2", pos = c(1, 1)) ## ----------------------------------------------------------------------------- mypalette <- RColorBrewer::brewer.pal(3, "Accent") eib.plot(he, graph = "base", line = list(color = mypalette)) eib.plot(he, graph = "ggplot2", line = list(color = mypalette)) ## ----echo=FALSE--------------------------------------------------------------- # create output docs # rmarkdown::render(input = "vignettes/eib.Rmd", output_format = "pdf_document", output_dir = "vignettes") # rmarkdown::render(input = "vignettes/eib.Rmd", output_format = "html_document", output_dir = "vignettes")
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/eib.R
--- title: "Expected Incremental Benefit Plot" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Expected Incremental Benefit Plot} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6, fig.height = 6 ) ``` ```{r setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE} library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ``` ## Introduction The intention of this vignette is to show how to plot different styles of expected incremental benefit (EIB) plots using the BCEA package. ## Two interventions only This is the simplest case, usually an alternative intervention ($i=1$) versus status-quo ($i=0$). The plot is based on the incremental benefit as a function of the willingness to pay $k$. $$ IB(\theta) = k \Delta_e - \Delta_c $$ Using the set of $S$ posterior samples, the EIB is approximated by $$ \frac{1}{S} \sum_s^S IB(\theta_s) $$ where $\theta_s$ is the realised configuration of the parameters $\theta$ in correspondence of the $s$-th simulation. #### R code To calculate these in BCEA we use the `bcea()` function. ```{r} data(Vaccine) he <- bcea(eff, cost, ref = 2, interventions = treats, Kmax = 50000, plot = FALSE) ``` The default EIB plot gives a single diagonal line using base R. ```{r} eib.plot(he) ``` The vertical line represents the break-even value corresponding to $k^*$ indicating that above that threshold the alternative treatment is more cost-effective than the status-quo. $$ k^* = \min\{ k : \mbox{EIB} > 0 \} $$ This will be at the point the curve crosses the _x_-axis. The plot defaults to base R plotting. Type of plot can be set explicitly using the `graph` argument. ```{r} eib.plot(he, graph = "base") eib.plot(he, graph = "ggplot2") # ceac.plot(he, graph = "plotly") ``` Other plotting arguments can be specified such as title, line colours and theme. ```{r} eib.plot(he, graph = "ggplot2", main = "my title", line = list(color = "green"), theme = theme_dark()) ``` Credible interval can also be plotted using the `plot.cri` logical argument. ```{r} eib.plot(he, plot.cri = FALSE) ``` ## Multiple interventions This situation is when there are more than two interventions to consider. Incremental values can be obtained either always against a fixed reference intervention, such as status quo, or for all comparisons simultaneously. The curves are for pair-wise comparisons against a status-quo and the vertical lines and k* annotation is for simultaneous comparisons. Without loss of generality, if we assume status quo intervention $i=0$, then we wish to calculate $$ \frac{1}{S} \sum_s^S IB(\theta^{i0}_s) \;\; \mbox{for each} \; i $$ The break-even points represent no preference between the two best interventions at $k$. $$ k^*_i = \min\{ k : \mbox{EIB}(\theta^i) > \mbox{EIB}(\theta^j) \} $$ Only the right-most of these will be where the curves cross the x-axis. #### R code This is the default plot for `eib.plot()` so we simply follow the same steps as above with the new data set. ```{r} data(Smoking) treats <- c("No intervention", "Self-help", "Individual counselling", "Group counselling") he <- bcea(eff, cost, ref = 4, interventions = treats, Kmax = 500) eib.plot(he) ``` For example, we can change the main title and the EIB line colours to green. ```{r} eib.plot(he, graph = "base", main = "my title", line = list(color = "green")) ``` ```{r} eib.plot(he, graph = "ggplot2", main = "my title", line = list(color = "green")) ``` Credible interval can also be plotted as before. This isn't recommended in this case since its hard to understand with so many lines. ```{r} eib.plot(he, plot.cri = TRUE) ``` ##### Repositioning the legend. For base R, ```{r} eib.plot(he, pos = FALSE) # bottom right eib.plot(he, pos = c(0, 0)) eib.plot(he, pos = c(0, 1)) eib.plot(he, pos = c(1, 0)) eib.plot(he, pos = c(1, 1)) ``` For `ggplot2`, ```{r} ##TODO: eib.plot(he, graph = "ggplot2", pos = c(0, 0)) eib.plot(he, graph = "ggplot2", pos = c(0, 1)) eib.plot(he, graph = "ggplot2", pos = c(1, 0)) eib.plot(he, graph = "ggplot2", pos = c(1, 1)) ``` Define colour palette for different colour for each EIB line. ```{r} mypalette <- RColorBrewer::brewer.pal(3, "Accent") eib.plot(he, graph = "base", line = list(color = mypalette)) eib.plot(he, graph = "ggplot2", line = list(color = mypalette)) ``` ```{r echo=FALSE} # create output docs # rmarkdown::render(input = "vignettes/eib.Rmd", output_format = "pdf_document", output_dir = "vignettes") # rmarkdown::render(input = "vignettes/eib.Rmd", output_format = "html_document", output_dir = "vignettes") ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/eib.Rmd
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ## ----setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE---------- library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ## ----------------------------------------------------------------------------- data("Smoking") he <- bcea(eff, cost, ref = 4, Kmax = 500) ## ----fig.height=10------------------------------------------------------------ par(mfrow = c(2,1)) ceac.plot(he) abline(h = 0.5, lty = 2) abline(v = c(160, 225), lty = 3) eib.plot(he, plot.cri = FALSE) ## ----------------------------------------------------------------------------- he.multi <- multi.ce(he) ## ----fig.height=10------------------------------------------------------------ par(mfrow = c(2, 1)) ceac.plot(he.multi) abline(h = 0.5, lty = 2) abline(v = c(160, 225), lty = 3) eib.plot(he, plot.cri = FALSE)
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/paired_vs_multiple_comps.R
--- title: "Paired vs Multiple Comparisons" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Paired vs Multiple Comparisons} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 6 ) ``` ```{r setup, results='hide', message=FALSE, warning=FALSE, echo=FALSE} library(BCEA) library(dplyr) library(reshape2) library(ggplot2) library(purrr) ``` ## Introduction The intention of this vignette is to show how to plot the CEAC and EIB plots depending on whether we consider all interventions simultaneously or pair-wise against a reference. ## Multiple interventions This situation is when there are more than two interventions to consider. Incremental values can be obtained either always against a fixed reference intervention, such as status-quo, or for all comparisons simultaneously. We will call these a paired comparison or a multiple comparison. ### Against a fixed reference intervention #### R code This is the default plot for `ceac.plot()` so we simply follow the same steps as above with the new data set. ```{r} data("Smoking") he <- bcea(eff, cost, ref = 4, Kmax = 500) ``` ```{r fig.height=10} par(mfrow = c(2,1)) ceac.plot(he) abline(h = 0.5, lty = 2) abline(v = c(160, 225), lty = 3) eib.plot(he, plot.cri = FALSE) ``` ### Pair-wise comparisons #### R code In _BCEA_ we first we must determine all combinations of paired interventions using the `multi.ce()` function. ```{r} he.multi <- multi.ce(he) ``` ```{r fig.height=10} par(mfrow = c(2, 1)) ceac.plot(he.multi) abline(h = 0.5, lty = 2) abline(v = c(160, 225), lty = 3) eib.plot(he, plot.cri = FALSE) ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/doc/paired_vs_multiple_comps.Rmd
--- title: "smoking-jags" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{smoking-jags} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(BCEA) ``` Load the R2jags package and the the data file ```{r} library(R2jags) ``` Specify the name of the jags model file. ```{r} model.file <- here::here("inst/jags/smoking_model_RE.txt") ``` Load smoking data. ```{r} data("Smoking") ``` Copy smoking data frame columns to local variables. ```{r} attach(smoking) nobs <- nobs s <- s t <- i r <- r_i n <- n_i b <- b_i + 1 detach(smoking) ``` ```{r} # number of trials ns <- length(unique(s)) # number of comparators nt <- length(unique(t)) # number of observations nobs <- dim(smoking)[1] # how many studies include baseline incb <- sum(table(s, b)[, 1] > 0) ``` Define data and parameters to monitor and run. ```{r} inputs <- list ("s", "n", "r", "t", "ns", "nt", "b", "nobs", "incb")#, "na") pars <- c("rr ", "pi ", "p", "d", "sd ")#, "T") smoking_output <- jags( data = inputs, inits = NULL, parameters.to.save = pars, model.file = model.file, n.burnin = 5000, n.chains = 2, n.iter = 10000, n.thin = 20) ``` ```{r} smoking_output ``` ```{r} save(smoking_output, file = here::here("inst/extdata/smoking_output.RData")) ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/jags/smoking-jags.Rmd
--- title: "Auto-generated report from BCEA" header-includes: \usepackage{graphicx} \usepackage{bm} date: "Version: `r format(Sys.time(), '%d %B, %Y')`" output: word_document: default pdf_document: fontsize: 11pt geometry: margin=1cm bibliography: biblio.bib nocite: | @Baioetal:2017 --- ```{r, echo=FALSE, warning=FALSE, message=FALSE, comment=NA} options(scipen = 999) align <- if (rmd_params$ext == "pdf") { "center" } else { "default" } # check whether Info-rank should also be computed & shown eval_IR <- if (!is.null(rmd_params$psa_sims)) { TRUE } else { FALSE} ``` ## Cost-effectiveness analysis The cost-effectiveness analysis is based on the maximisation of the expected utility, defined as the _monetary net benefit_ $nb_t=ke_t-c_t$. Here $t$ indicates one of the interventions (treatments) being assessed, while $(e,c)$ indicate the relevant measures of _effectiveness_ and _cost_. For each intervention, the expected utility is computed as $\mathcal{NB}_t=k\mbox{E}[e_t]-\mbox{E}[c_t]$. When comparing two interventions (say, $t=1$ vs $t=0$), or using a pairwise comparison, we can determine the ``best'' alternative by considering the difference in the expected utilities $\mbox{EIB}=\mathcal{NB}_1-\mathcal{NB}_0$. This can also be expressed in terms of the _population effectiveness and cost differentials_ $\mbox{EIB}=k\mbox{E}[\Delta_e]-\mbox{E}[\Delta_c]$, where $\Delta_e=\mbox{E}[e\mid\bm\theta_1]-\mbox{E}[e\mid\bm\theta_0]$ and $\Delta_c=\mbox{E}[c\mid\bm\theta_1]-\mbox{E}[c\mid\bm\theta_0]$ are the average effectiveness and cost, as function of the relevant model parameters $\bm\theta=(\bm\theta_0,\bm\theta_1)$. This sub-section presents a summary table reporting basic economic results as well as the optimal decision, given the selected willingness-to-pay threshold $k=$`r rmd_params$wtp`. The table below presents a summary of the optimal decision, as well as the values of the Expected Incremental Benefit $\mbox{EIB}=k\mbox{E}[\Delta_e]-\mbox{E}[\Delta_c]$, Cost-Effectiveness Acceptability Curve $\mbox{CEAC}=\Pr(k\Delta_e-\Delta_c)$ and Incremental Cost-Effectiveness Ratio $\mbox{ICER}=\displaystyle\frac{\mbox{E}[\Delta_c]}{\mbox{E}[\Delta_e]}$, for the set willingness-to-pay value. ```{r, echo=echo, warning=FALSE, message=FALSE, comment=NA} summary(m, wtp = rmd_params$wtp) ``` ```{r child = 'section_ceplane.Rmd'} ``` ```{r child = 'section_EIB.Rmd'} ``` ```{r child = 'section_CEAC.Rmd'} ``` ```{r child = 'section_CEAF.Rmd'} ``` ```{r child = 'section_CEEF.Rmd'} ``` ```{r child = 'section_EVPI.Rmd'} ``` ```{r child = 'section_InfoRank.Rmd', eval=eval_IR} ``` ## References
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/rmarkdown/report/report.Rmd
## Cost-effectiveness acceptability curve The _Cost-Effectiveness Acceptability Curve_ (CEAC) estimates the probability of cost-effectiveness, for different willingness to pay thresholds. The CEAC is used to evaluate the uncertainty associated with the decision-making process, since it quantifies the degree to which a treatment is preferred. This is measured in terms of the difference in utilities, normally the incremental benefit. Effectively, the CEAC represents the proportion of simulations in which $t=1$ is associated with a higher utility than $t=0$. The following graph shows the cost-effectiveness acceptability curve (CEAC). The CEAC represents the proportion of 'potential futures' in which the reference intervention is estimated to be more cost-effective than the comparator. Thus, it can be interpreted as the 'probability of cost-effectiveness'. ```{r, echo=echo, fig.width=4.6, fig.height=4.6, fig.align=align, warning=FALSE, message=FALSE, comment=NA} ceac.plot(m) ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/rmarkdown/report/section_CEAC.Rmd
## Cost-effectiveness acceptability frontier In addition to the CEAC, we can also visualise the uncertainty in the decision-making process using the _Cost-Effectiveness Acceptability Frontier_ (CEAF). The frontier is defined as the maximum value of the probability of cost-effectiveness among all comparators. It is an indication of the uncertainty associated with choosing the cost effective intervention. In other terms, higher frontier values correspond to lower decision uncertainty. ```{r, echo=echo, fig.width=4.6, fig.height=4.6, fig.align=align, warning=FALSE, message=FALSE, comment=NA} n.ints <- m$n_comparators if (n.ints == 2) { graph <- "base" pos <- c(1, 1) } else { graph <- "ggplot2" pos <- TRUE } ceaf.plot(multi.ce(m), graph = graph) ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/rmarkdown/report/section_CEAF.Rmd
## Cost-effectiveness efficiency frontier The _Cost-Effectiveness Efficiency Frontier_ (CEEF) compares the net costs and benefits of different interventions in a given therapeutic area. It is different from the common differential approach (e.g. based on the Cost-Effectiveness plane), because it is based on the _net_ measures. The predicted costs and effectiveness for the interventions under consideration are compared directly to the costs and effectiveness for the treatments that are currently available. The frontier in itself defines the set of interventions for which cost is at an acceptable level for the benefits given by the treatment. A new intervention is _efficient_ if its average effectiveness is greater than any of the currently available alternatives, or its cost are lower than that associated with other interventions of the same effectiveness. In the following plot, the circles indicate the mean for the cost and effectiveness distributions for each treatment option. The number in each circle corresponds to the order of the treatments in the legend. If the number is black then the intervention is on the efficiency frontier. Grey numbers indicate dominated treatments. ```{r, echo=echo, comment=" ", warning=FALSE, message=FALSE, fig.width=4.6, fig.height=4.6, fig.align=align, warning=FALSE, message=FALSE, comment=NA} n.ints <- m$n_comparators if (n.ints == 2) { graph <- "base" pos <- c(1, 1) } else { graph <- "ggplot2" pos <- TRUE } ceef.plot(m, graph = graph) ``` The summary is composed of two tables, reporting information for the comparators included on the frontier. It also details the average health effects and costs for the comparators not on the frontier, if any. For the interventions included on the frontier, the slope of the frontier segment connecting the intervention to the previous efficient one and the angle inclination of the segment (with respect to the $x-$axis), measured in radians, are also reported. In particular, the slope can be interpreted as the increase in costs for an additional unit in effectiveness, i.e. the ICER for the comparison against the previous treatment. The dominance type for comparators not on the efficiency frontier is reported in the output table. This can be of two types: absolute or extended dominance. An intervention is absolutely dominated if another comparator has both lower costs and greater health benefits, i.e. the ICER for at least one pairwise comparison is negative. Comparators in a situation of extended dominance are not wholly inefficient, but are dominated because a combination of two other interventions will provide more benefits for lower costs.
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/rmarkdown/report/section_CEEF.Rmd
## Expected Incremental Benefit The following graph shows the _Expected Incremental Benefit_ (EIB), as a function of a grid of values for the willingness to pay $k$ (in this case in the interval `r min(m$k)` - `r max(m$k)`). The EIB can be directly linked with the decision rule applied to the ICER. If a willingness to pay value $k^*$ exists in correspondence of which $\mbox{EIB}=0$ this value of $k$ is called the _break-even point_. It corresponds to the maximum uncertainty associated with the decision between the two comparators, with equal expected utilities for the two interventions. In other terms, for two willingness to pay values, one greater and one less than $k^*$, there will be two different optimal decisions. The graph also reports the 95% credible limits around the EIB. ```{r, echo=echo, fig.width=4.6, fig.height=4.6, fig.align=align, warning=FALSE, message=FALSE, comment=NA} n.ints <- m$n_comparators if (n.ints == 2) { graph <- "base" pos <- c(1, 1) } else { graph <- "ggplot2" pos <- TRUE } eib.plot(m, graph = graph, pos = pos) ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/rmarkdown/report/section_EIB.Rmd
## Expected value of perfect information One measure to quantify the value of additional information is known as the _Expected Value of Perfect Information_ (EVPI). This measure translates the uncertainty associated with the cost-effectiveness evaluation in the model into an economic quantity. This quantification is based on the _Opportunity Loss_ (OL), which is a measure of the potential losses caused by choosing the most cost-effective intervention _on average_ when it does not result in the intervention with the highest utility in a 'possible future'. A future can be thought of as obtaining enough data to know the exact value of the utilities for the different interventions. This would allow the decision makers to known the optimal treatment with certainty. The opportunity loss occurs when the optimal treatment on average is non-optimal for a specific point in the distribution for the utilities. To calculate the EVPI practically, possible futures for the different utilities are represented by the simulations. The utility values in each simulation are assumed to be known, corresponding to a possible future, which could happen with a probability based on the current available knowledge included in and represented by the model. The opportunity loss is the difference between the maximum value of the simulation-specific (known-distribution) utility $\mbox{NB}^*(\bm\theta)=k\Delta_e-\Delta_c$ and the utility for the intervention resulting in the overall maximum expected utility $\mbox{NB}(\bm\theta^\tau)$, where $\tau=\text{arg max}_t ~\mathcal{NB}^t$. Usually, for a large number simulations the OL will be 0 as the optimal treatment on average will also be the optimal treatment for the majority of simulations. This means that the opportunity loss is always positive as either we choose the current optimal treatment or the treatment with a higher utility value for that specific simulation. The EVPI is then defined as the average of the opportunity loss. This measures the average potential losses in utility caused by the simulation specific optimal decision being non-optimal in reality. If the probability of cost-effectiveness is low then more simulations will give a non-zero opportunity loss and consequently the EVPI will be higher. This means that if the probability of cost-effectiveness is very high, it is unlikely that more information would be worthwhile, as the most cost-effective treatment is already evident. However, the EVPI gives additional information over the EVPI as it takes into account the opportunity lost as well as simply the probability of cost-effectiveness. For example, there may be a setting where the probability of cost-effectiveness is low, so the decision maker believes that decision uncertainty is important. However, this is simply because the two treatments are very similar in both costs and effectiveness. In this case the OL will be low as the utilities will be similar for both treatments for all simulations. Therefore, the cost of making the incorrect decision is very low. This will be reflected in the EVPI but not in the CEAC and implies that the optimal treatment can be chosen with little financial risk, even with a low probability of cost-effectiveness. ```{r, echo=echo, fig.width=4.6, fig.height=4.6, fig.align=align, warning=FALSE, message=FALSE, comment=NA} evi.plot(m) ```
/scratch/gouwar.j/cran-all/cranData/BCEA/inst/rmarkdown/report/section_EVPI.Rmd