-
Notifications
You must be signed in to change notification settings - Fork 5
/
Functions.R
2131 lines (1953 loc) · 77.8 KB
/
Functions.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#----------------------------------------------------------------------------#
#### Function to plot cohort trace ####
#----------------------------------------------------------------------------#
#' Plot cohort trace
#'
#' \code{plot_trace} plots the cohort trace.
#'
#' @param m_M a cohort trace matrix
#' @return a ggplot object - plot of the cohort trace
#'
plot_trace <- function(m_M) {
df_M <- data.frame(Cycle = 0:n_cycles, m_M, check.names = F)
df_M_long <- tidyr::gather(df_M, key = `Health State`, value, 2:ncol(df_M))
df_M_long$`Health State` <- factor(df_M_long$`Health State`, levels = v_names_states)
gg_trace <- ggplot(df_M_long, aes(x = Cycle, y = value,
color = `Health State`, linetype = `Health State`)) +
geom_line(size = 1) +
xlab("Cycle") +
ylab("Proportion of the cohort") +
scale_x_continuous(breaks = number_ticks(8)) +
theme_bw(base_size = 14) +
theme(legend.position = "bottom",
legend.background = element_rect(fill = NA))
return(gg_trace)
}
#----------------------------------------------------------------------------#
#### Function to plot cohort trace per strategy ####
#----------------------------------------------------------------------------#
#' Plot cohort trace per strategy
#'
#' \code{plot_trace} plots the cohort trace for each strategy, split by health state.
#'
#' @param l_m_M a list containing cohort trace matrices
#' @return a ggplot object - plot of the cohort trace for each strategy split by health state.
#'
plot_trace_strategy <- function(l_m_M) {
n_str <- length(l_m_M)
l_df_M <- lapply(l_m_M, as.data.frame)
df_M_strategies <- data.table::rbindlist(l_df_M, use.names = T,
idcol = "Strategy")
df_M_strategies$Cycle <- rep(0:n_cycles, n_str)
m_M_plot <- tidyr::gather(df_M_strategies, key = `Health State`, value,
2:(ncol(df_M_strategies)-1))
m_M_plot$`Health State` <- factor(m_M_plot$`Health State`, levels = v_names_states)
m_M_plot$Strategy <- factor(m_M_plot$Strategy, levels = v_names_str)
p <- ggplot(m_M_plot, aes(x = Cycle, y = value,
color = Strategy, linetype = Strategy)) +
geom_line(size = 1) +
scale_color_brewer(palette="RdBu") +
xlab("Cycle") +
ylab("Proportion of the cohort") +
theme_bw(base_size = 14) +
theme(legend.position = "bottom",
legend.background = element_rect(fill = NA)) +
facet_wrap(~ `Health State`)
return(p)
}
#----------------------------------------------------------------------------#
#### Function to calculate survival probabilities ####
#----------------------------------------------------------------------------#
#' Calculate survival probabilities
#'
#' \code{calc_surv} calculates the survival probabilities.
#'
#' @param l_m_M a list containing cohort trace matrices
#' @return a dataframe containing survival probabilities for each strategy
#'
calc_surv <- function(l_m_M, v_names_death_states) {
df_surv <- as.data.frame(lapply(l_m_M,
function(x) {
rowSums(x[, !colnames(x) %in% v_names_death_states])
}
))
colnames(df_surv) <- v_names_str
df_surv$Cycle <- 0:n_cycles
df_surv_long <- tidyr::gather(df_surv, key = Strategy, Survival, 1:n_str)
df_surv_long$Strategy <- ordered(df_surv_long$Strategy, levels = v_names_str)
df_surv_long <- df_surv_long %>%
select(Strategy, Cycle, Survival)
return(df_surv_long)
}
#----------------------------------------------------------------------------#
#### Function to calculate state proportions ####
#----------------------------------------------------------------------------#
#' Calculate state proportions
#'
#' \code{calc_surv} calculates the proportions of the cohort in specified states
#'
#' @param l_m_M a list containing cohort trace matrices
#' @return a dataframe containing proportions in specified states for each strategy
#'
calc_sick <- function(l_m_M, v_names_sick_states) {
n_sick_states <- length(v_names_sick_states)
df_sick <- as.data.frame(lapply(l_m_M,
function(x) {
if (n_sick_states == 1) {
x[, colnames(x) %in% v_names_sick_states]
} else {
rowSums(x[, colnames(x) %in% v_names_sick_states])
}
}
))
colnames(df_sick) <- v_names_str
df_sick$Cycle <- 0:n_cycles
df_sick_long <- tidyr::gather(df_sick, key = Strategy, Sick, 1:n_str)
df_sick_long$Strategy <- ordered(df_sick_long$Strategy, levels = v_names_str)
df_sick_long <- df_sick_long %>%
select(Strategy, Cycle, Sick)
return(df_sick_long)
}
#----------------------------------------------------------------------------#
#### Function to calculate prevalence ####
#----------------------------------------------------------------------------#
#' Calculate prevalence
#'
#' \code{plot_prevalence} calculate the prevalence for different health states.
#'
#' @param l_m_M a list containing cohort trace matrices
#' @return a dataframe containing prevalence of specified health states for each strategy
#'
calc_prevalence <- function(l_m_M, v_names_sick_states, v_names_dead_states) {
df_alive <- calc_surv(l_m_M, v_names_dead_states)
df_prop_sick <- calc_sick(l_m_M, v_names_sick_states)
df_prevalence <- data.frame(Strategy = df_alive$Strategy,
Cycle = df_alive$Cycle,
Prevalence = df_prop_sick$Sick / df_alive$Survival)
return(df_prevalence)
}
#----------------------------------------------------------------------------#
#### Function to calculate state-in-state proportions ####
#----------------------------------------------------------------------------#
#' Calculate state-in-state proportions
#'
#' \code{plot_prevalence} calculates the proportion of a speciefied subset of states among a set of specified states
#'
#' @param l_m_M a list containing cohort trace matrices
#' @return a dataframe containing state-in-state proportions of specified health states for each strategy
#'
calc_prop_sicker <- function(l_m_M, v_names_sick_states, v_names_sicker_states) {
df_prop_sick <- calc_sick(l_m_M, v_names_sick_states)
df_prop_sicker <- calc_sick(l_m_M, v_names_sicker_states)
df_prop_sick_sicker <- data.frame(Strategy = df_prop_sick$Strategy,
Cycle = df_prop_sick$Cycle,
`Proportion Sicker` =
df_prop_sicker$Sick /
(df_prop_sick$Sick + df_prop_sicker$Sick))
return(df_prop_sick_sicker)
}
#----------------------------------------------------------------------------#
#### Function to plot survival curve ####
#----------------------------------------------------------------------------#
#' Plot survival curve
#'
#' \code{plot_surv} plots the survival probability curve.
#'
#' @param l_m_M a list containing cohort trace matrices
#' @return a ggplot object - plot of the survival curve
#'
plot_surv <- function(l_m_M, v_names_death_states) {
df_surv <- calc_surv(l_m_M, v_names_death_states)
df_surv$Strategy <- factor(df_surv$Strategy, levels = v_names_str)
df_surv$Survival <- round(df_surv$Survival, 2)
p <- ggplot(df_surv,
aes(x = Cycle, y = Survival, group = Strategy)) +
geom_line(aes(linetype = Strategy, col = Strategy), size = 1.2) +
scale_color_brewer(palette="RdBu") +
xlab("Cycle") +
ylab("Proportion") +
ggtitle("Survival probabilities") +
theme_bw(base_size = 14) +
theme()
return(p)
}
#----------------------------------------------------------------------------#
#### Function to plot prevalence curve ####
#----------------------------------------------------------------------------#
#' Plot prevalence curve
#'
#' \code{plot_prevalence} plots the prevalence curve for specified health states.
#'
#' @param l_m_M a list containing cohort trace matrices
#' @return a ggplot object - plot of the prevalence curve
#'
plot_prevalence <- function(l_m_M, v_names_sick_states, v_names_dead_states) {
df_prevalence <- calc_prevalence(l_m_M, v_names_sick_states, v_names_dead_states)
df_prevalence$Strategy <- factor(df_prevalence$Strategy, levels = v_names_str)
df_prevalence$Proportion.Sicker <- round(df_prevalence$Prevalence, 2)
p <- ggplot(df_prevalence,
aes(x = Cycle, y = Prevalence, group = Strategy)) +
geom_line(aes(linetype = Strategy, col = Strategy), size = 1.2) +
scale_color_brewer(palette = "RdBu") +
xlab("Cycle") +
ylab("Proportion") +
ggtitle(paste("Prevalence", "of", paste(v_names_sick_states, collapse = " "))) +
theme_bw(base_size = 14) +
theme()
return(p)
}
#----------------------------------------------------------------------------#
#### Function to plot state-in-state proportion curve ####
#----------------------------------------------------------------------------#
#' Plot state-in-state proportion curve
#'
#' \code{plot_prevalence} plots the
#'
#' @param l_m_M a list containing cohort trace matrices
#' @return a ggplot object - plot of state-in-state proportion curve
#'
plot_proportion_sicker <- function(l_m_M, v_names_sick_states, v_names_sicker_states) {
df_proportion_sicker <- calc_prop_sicker(l_m_M, v_names_sick_states, v_names_sicker_states)
df_proportion_sicker$Strategy <- factor(df_proportion_sicker$Strategy, levels = v_names_str)
df_proportion_sicker$Proportion.Sicker <- round(df_proportion_sicker$Proportion.Sicker, 2)
p <- ggplot(df_proportion_sicker,
aes(x = Cycle, y = Proportion.Sicker, group = Strategy)) +
geom_line(aes(linetype = Strategy, col = Strategy), size = 1.2, na.rm = T) +
scale_color_brewer(palette = "RdBu") +
xlab("Cycle") +
ylab("Proportion") +
ggtitle(paste(paste("Proportion of", v_names_sicker_states),
paste(c("among", v_names_sick_states), collapse = " "))) +
theme_bw(base_size = 14) +
theme()
return(p)
}
#----------------------------------------------------------------------------#
#### Function to format CEA table ####
#----------------------------------------------------------------------------#
#' Format CEA table
#'
#' \code{format_table_cea} formats the CEA table.
#'
#' @param table_cea a dataframe object - table with CEA results
#' @return a dataframe object - formatted CEA table
#'
format_table_cea <- function(table_cea) {
colnames(table_cea)[colnames(table_cea)
%in% c("Cost",
"Effect",
"Inc_Cost",
"Inc_Effect",
"ICER")] <-
c("Costs ($)",
"QALYs",
"Incremental Costs ($)",
"Incremental QALYs",
"ICER ($/QALY)")
table_cea$`Costs ($)` <- comma(round(table_cea$`Costs ($)`, 0))
table_cea$`Incremental Costs ($)` <- comma(round(table_cea$`Incremental Costs ($)`, 0))
table_cea$QALYs <- round(table_cea$QALYs, 2)
table_cea$`Incremental QALYs` <- round(table_cea$`Incremental QALYs`, 2)
table_cea$`ICER ($/QALY)` <- comma(round(table_cea$`ICER ($/QALY)`, 0))
return(table_cea)
}
#' Update parameters
#'
#' \code{update_param_list} is used to update list of all parameters with new
#' values for specific parameters.
#'
#' @param l_params_all List with all parameters of decision model
#' @param params_updated Parameters for which values need to be updated
#' @return
#' A list with all parameters updated.
#' @export
update_param_list <- function(l_params_all, params_updated){
if (typeof(params_updated)!="list"){
params_updated <- split(unname(params_updated),names(params_updated)) #converte the named vector to a list
}
l_params_all <- modifyList(l_params_all, params_updated) #update the values
return(l_params_all)
}
################################################################################
################# FUNCTIONS INCLUDED IN DARTHTOOLS #############################
################################################################################
#' Within-cycle correction (WCC)
#'
#' \code{gen_wcc} generates a vector of within-cycle corrections (WCC).
#'
#' @param n_cycles number of cycles
#' @param method The method to be used for within-cycle correction.
#'
#' @return A vector of length \code{n_cycles + 1} with within-cycle corrections
#'
#' @details
#' The default method is an implementation of Simpson's 1/3rd rule that
#' generates a vector with the first and last entry with 1/3 and the odd and
#' even entries with 4/3 and 2/3, respectively.
#'
#' Method "\code{half-cycle}" is the half-cycle correction method that
#' generates a vector with the first and last entry with 1/2 and the rest equal
#' to 1.
#'
#' Method "\code{none}" does not implement any within-cycle correction and
#' generates a vector with ones.
#'
#' @references
#' \enumerate{
#' \item Elbasha EH, Chhatwal J. Myths and misconceptions of within-cycle
#' correction: a guide for modelers and decision makers. Pharmacoeconomics.
#' 2016;34(1):13-22.
#' \item Elbasha EH, Chhatwal J. Theoretical foundations and practical
#' applications of within-cycle correction methods. Med Decis Mak.
#' 2016;36(1):115-131.
#' }
#'
#' @examples
#' # Number of cycles
#' n_cycles <- 10
#' gen_wcc(n_cycles = n_cycles, method = "Simpson1/3")
#' gen_wcc(n_cycles = n_cycles, method = "half-cycle")
#' gen_wcc(n_cycles = n_cycles, method = "none")
#'
#' @export
gen_wcc <- function (n_cycles, method = c("Simpson1/3", "half-cycle", "none"))
{
if (n_cycles <= 0) {
stop("Number of cycles should be positive")
}
method <- match.arg(method)
n_cycles <- as.integer(n_cycles)
if (method == "Simpson1/3") {
v_cycles <- seq(1, n_cycles + 1)
v_wcc <- ((v_cycles%%2) == 0) * (2/3) + ((v_cycles%%2) !=
0) * (4/3)
v_wcc[1] <- v_wcc[n_cycles + 1] <- 1/3
}
if (method == "half-cycle") {
v_wcc <- rep(1, n_cycles + 1)
v_wcc[1] <- v_wcc[n_cycles + 1] <- 0.5
}
if (method == "none") {
v_wcc <- rep(1, n_cycles + 1)
}
return(v_wcc)
}
function (r, t = 1)
{
if ((sum(r < 0) > 0)) {
stop("rate not greater than or equal to 0")
}
p <- 1 - exp(-r * t)
return(p)
}
#' Convert a rate to a probability
#'
#' \code{rate_to_prob} convert a rate to a probability.
#'
#' @param r rate
#' @param t time/ frequency
#' @return a scalar or vector with probabilities
#' @examples
#' # Annual rate to monthly probability
#' r_year <- 0.3
#' r_month <- rate_to_prob(r = r_year, t = 1/12)
#' r_month
#' @export
rate_to_prob <- function(r, t = 1){
if ((sum(r < 0) > 0)){
stop("rate not greater than or equal to 0")
}
p <- 1 - exp(- r * t)
return(p)
}
#' Check if transition array is valid
#'
#' \code{check_transition_probability} checks if transition probabilities are in \[0, 1\].
#'
#' @param a_P A transition probability array/ matrix.
#' @param err_stop Logical variable to stop model run if set up as TRUE. Default = FALSE.
#' @param verbose Logical variable to indicate print out of messages.
#' Default = FALSE
#'
#' @return
#' This function stops if transition probability array is not valid and shows
#' what are the entries that are not valid
#' @export
check_transition_probability <- function(a_P,
err_stop = FALSE,
verbose = FALSE) {
a_P <- as.array(a_P)
# Verify if a_P is 2D or 3D matrix
n_dim <- length(dim(a_P))
# If a_P is a 2D matrix, convert to a 3D array
if (n_dim < 3){
a_P <- array(a_P, dim = list(nrow(a_P), ncol(a_P), 1),
dimnames = list(rownames(a_P), colnames(a_P), "Time independent"))
}
# Check which entries are not valid
m_indices_notvalid <- arrayInd(which(a_P < 0 | a_P > 1),
dim(a_P))
if(dim(m_indices_notvalid)[1] != 0){
v_rows_notval <- rownames(a_P)[m_indices_notvalid[, 1]]
v_cols_notval <- colnames(a_P)[m_indices_notvalid[, 2]]
v_cycles_notval <- dimnames(a_P)[[3]][m_indices_notvalid[, 3]]
df_notvalid <- data.frame(`Transition probabilities not valid:` =
matrix(paste0(paste(v_rows_notval, v_cols_notval, sep = "->"),
"; at cycle ",
v_cycles_notval), ncol = 1),
check.names = FALSE)
if(err_stop) {
stop("Not valid transition probabilities\n",
paste(capture.output(df_notvalid), collapse = "\n"))
}
if(verbose){
warning("Not valid transition probabilities\n",
paste(capture.output(df_notvalid), collapse = "\n"))
}
}
}
#' Check if the sum of transition probabilities equal to one.
#'
#' \code{check_sum_of_transition_array} checks if each of the rows of the
#' transition matrices sum to one.
#'
#' @param a_P A transition probability array/ matrix.
#' @param n_states Number of health states in a Markov trace, appropriate for Markov models.
#' @param n_rows Number of rows (individuals), appropriate for microsimulation models.
#' @param n_cycles Number of cycles.
#' @param err_stop Logical variable to stop model run if set up as TRUE.
#' Default = TRUE.
#' @param verbose Logical variable to indicate print out of messages.
#' Default = TRUE
#' @return
#' The transition probability array and the cohort trace matrix.
#' @export
check_sum_of_transition_array <- function(a_P,
n_rows = NULL,
n_states = NULL,
n_cycles,
err_stop = TRUE,
verbose = TRUE) {
if (!is.null(n_rows) & !is.null(n_states)) {
stop("Pick either n_rows or n_states, not both.")
}
if (is.null(n_rows) & is.null(n_states)) {
stop("Need to specify either n_rows or n_states, but not both.")
}
if (!is.null(n_rows)) {
n_states <- n_rows
}
a_P <- as.array(a_P)
d <- length(dim(a_P))
# For matrix
if (d == 2) {
valid <- sum(rowSums(a_P))
if (abs(valid - n_states) > 0.01) {
if(err_stop) {
stop("This is not a valid transition matrix")
}
if(verbose){
warning("This is not a valid transition matrix")
}
}
} else {
# For array
valid <- (apply(a_P, d, function(x) sum(rowSums(x))) == n_states)
if (!isTRUE(all.equal(as.numeric(sum(valid)), as.numeric(n_cycles)))) {
if(err_stop) {
stop("This is not a valid transition array")
}
if(verbose){
warning("This is not a valid transition array")
}
}
}
}
################################################################################
################## FUNCTIONS INCLUDED IN DAMPACK ###############################
################################################################################
# For a more detailed description and current versions of the functions above,
# please go to dampack's package Github repo (https://github.com/DARTH-git/dampack)
#' Cost-Effectiveness Acceptability Curve (CEAC)
#'
#' \code{ceac} is used to compute and plot the cost-effectiveness acceptability
#' curves (CEAC) from a probabilistic sensitivity analysis (PSA) dataset.
#'
#' @param wtp numeric vector with willingness-to-pay (WTP) thresholds
#' @param psa psa object from \code{\link{make_psa_obj}}
#' @keywords cost-effectiveness acceptability curves
#' @details
#' \code{ceac} computes the probability of each of the strategies being
#' cost-effective at each \code{wtp} threshold. The returned object has classes
#' \code{ceac} and \code{data.frame}, and has its own plot method (\code{\link{plot.ceac}}).
#'
#' @return An object of class \code{ceac} that can be visualized with \code{plot}. The \code{ceac}
#' object is a data.frame that shows the proportion of PSA samples for which each strategy at each
#' WTP threshold is cost-effective. The final column indicates whether or not the strategy at a
#' particular WTP is on the cost-efficient frontier.
#'
#' @examples
#' # psa input provided with package
#' data("example_psa")
#' example_psa_obj <- make_psa_obj(example_psa$cost, example_psa$effectiveness,
#' example_psa$parameters, example_psa$strategies)
#'
#' # define wtp threshold vector (can also use a single wtp)
#' wtp <- seq(1e4, 1e5, by = 1e4)
#' ceac_obj <- ceac(wtp, example_psa_obj)
#' plot(ceac_obj) # see ?plot.ceac for options
#'
#' # this is most useful when there are many strategies
#' # warnings are printed to describe strategies that
#' # have been filtered out
#' plot(ceac_obj, min_prob = 0.5)
#'
#' # standard ggplot layers can be used
#' plot(ceac_obj) +
#' labs(title = "CEAC", y = "Pr(Cost-effective) at WTP")
#'
#' # the ceac object is also a data frame
#' head(ceac_obj)
#'
#' # summary() tells us the regions of cost-effectiveness for each strategy.
#' # Note that the range_max column is an open parenthesis, meaning that the
#' # interval over which that strategy is cost-effective goes up to but does not include
#' # the value in the range_max column.
#' summary(ceac_obj)
#'
#' @seealso
#' \code{\link{plot.ceac}}, \code{\link{summary.ceac}}
#'
#'
#' @importFrom tidyr pivot_longer
#' @export
ceac <- function(wtp, psa) {
# check that psa has class 'psa'
check_psa_object(psa)
# define needed variables
strategies <- psa$strategies
n_strategies <- psa$n_strategies
effectiveness <- psa$effectiveness
cost <- psa$cost
n_sim <- psa$n_sim
# number of willingness to pay thresholds
n_wtps <- length(wtp)
# matrix to store probability optimal for each strategy
cea <- matrix(0, nrow = n_wtps, ncol = n_strategies)
colnames(cea) <- strategies
# vector to store strategy at the cost-effectiveness acceptability frontier
frontv <- rep(0, n_wtps)
for (l in 1:n_wtps) {
# calculate net monetary benefit at wtp[l]
lth_wtp <- wtp[l]
nmb <- calculate_outcome("nmb", cost, effectiveness, lth_wtp)
# find the distribution of optimal strategies
max.nmb <- max.col(nmb)
opt <- table(max.nmb)
cea[l, as.numeric(names(opt))] <- opt / n_sim
# calculate point on CEAF
# the strategy with the highest expected nmb
frontv[l] <- which.max(colMeans(nmb))
}
# make cea df
cea_df <- data.frame(wtp, cea, strategies[frontv],
stringsAsFactors = FALSE)
colnames(cea_df) <- c("WTP", strategies, "fstrat")
# Reformat df to long format
ceac <- tidyr::pivot_longer(
data = cea_df,
cols = !c("WTP", "fstrat"),
names_to = "Strategy",
values_to = "Proportion"
)
# boolean for on frontier or not
ceac$On_Frontier <- (ceac$fstrat == ceac$Strategy)
# drop fstrat column
ceac$fstrat <- NULL
# order by WTP
ceac <- ceac[order(ceac$WTP), ]
# remove rownames
rownames(ceac) <- NULL
# make strategies in ceac object into ordered factors
ceac$Strategy <- factor(ceac$Strategy, levels = strategies, ordered = TRUE)
# define classes
# defining data.frame as well allows the object to use print.data.frame, for example
class(ceac) <- c("ceac", "data.frame")
return(ceac)
}
#' Plot of Cost-Effectiveness Acceptability Curves (CEAC)
#'
#' Plots the CEAC, using the object created by \code{\link{ceac}}.
#'
#' @param x object of class \code{ceac}.
#' @param frontier whether to plot acceptability frontier (TRUE) or not (FALSE)
#' @param points whether to plot points (TRUE) or not (FALSE)
#' @param currency string with currency used in the cost-effectiveness analysis (CEA).
#'Defaults to \code{$}, but can be any currency symbol or word (e.g., £, €, peso)
#' @param min_prob minimum probability to show strategy in plot.
#' For example, if the min_prob is 0.05, only strategies that ever
#' exceed Pr(Cost Effective) = 0.05 will be plotted. Most useful in situations
#' with many strategies.
#' @inheritParams add_common_aes
#'
#' @keywords internal
#'
#' @details
#' \code{ceac} computes the probability of each of the strategies being
#' cost-effective at each \code{wtp} value.
#' @return A \code{ggplot2} plot of the CEAC.
#'
#' @import ggplot2
#' @import dplyr
#'
#' @export
plot.ceac <- function(x,
frontier = TRUE,
points = TRUE,
currency = "$",
min_prob = 0,
txtsize = 12,
n_x_ticks = 10,
n_y_ticks = 8,
xbreaks = NULL,
ybreaks = NULL,
ylim = NULL,
xlim = c(0, NA),
col = c("full", "bw"),
...) {
wtp_name <- "WTP"
prop_name <- "Proportion"
strat_name <- "Strategy"
x$WTP_thou <- x[, wtp_name] / 1000
# removing strategies with probabilities always below `min_prob`
# get group-wise max probability
if (min_prob > 0) {
max_prob <- x %>%
group_by(.data$Strategy) %>%
summarize(maxpr = max(.data$Proportion)) %>%
filter(.data$maxpr >= min_prob)
strat_to_keep <- max_prob$Strategy
if (length(strat_to_keep) == 0) {
stop(
paste("no strategies remaining. you may want to lower your min_prob value (currently ",
min_prob, ")", sep = "")
)
}
# report filtered out strategies
old_strat <- unique(x$Strategy)
diff_strat <- setdiff(old_strat, strat_to_keep)
n_diff_strat <- length(diff_strat)
if (n_diff_strat > 0) {
# report strategies filtered out
cat("filtered out ", n_diff_strat, " strategies with max prob below ", min_prob, ":\n",
paste(diff_strat, collapse = ","), "\n", sep = "")
# report if any filtered strategies are on the frontier
df_filt <- filter(x, .data$Strategy %in% diff_strat & .data$On_Frontier)
if (nrow(df_filt) > 0) {
cat(paste0("WARNING - some strategies that were filtered out are on the frontier:\n",
paste(unique(df_filt$Strategy), collapse = ","), "\n"))
}
}
# filter dataframe
x <- filter(x, .data$Strategy %in% strat_to_keep)
}
# Drop unused strategy names
x$Strategy <- droplevels(x$Strategy)
p <- ggplot(data = x, aes_(x = as.name("WTP_thou"),
y = as.name(prop_name),
color = as.name(strat_name))) +
geom_line() +
xlab(paste("Willingness to Pay (Thousand ", currency, " / QALY)", sep = "")) +
ylab("Pr Cost-Effective")
if (points) {
p <- p + geom_point(aes_(color = as.name(strat_name)))
}
if (frontier) {
front <- x[x$On_Frontier, ]
p <- p + geom_point(data = front, aes_(x = as.name("WTP_thou"),
y = as.name(prop_name),
shape = as.name("On_Frontier")),
size = 3, stroke = 1, color = "black") +
scale_shape_manual(name = NULL, values = 0, labels = "Frontier") +
guides(color = guide_legend(order = 1),
shape = guide_legend(order = 2))
}
col <- match.arg(col)
add_common_aes(p, txtsize, col = col, col_aes = "color",
continuous = c("x", "y"), n_x_ticks = n_x_ticks, n_y_ticks = n_y_ticks,
xbreaks = xbreaks, ybreaks = ybreaks,
ylim = ylim, xlim = xlim)
}
#' Summarize a ceac
#'
#' Describes cost-effective strategies and their
#' associated intervals of cost-effectiveness
#'
#' @param object object returned from the \code{ceac} function
#' @param ... further arguments (not used)
#' @return data frame showing the interval of cost effectiveness for each
#' interval. The intervals are open on the right endpoint -
#' i.e., [\code{range_min}, \code{range_max})
#'
#' @keywords internal
#'
#' @export
summary.ceac <- function(object, ...) {
front <- object[object$On_Frontier == TRUE, ]
front$Strategy <- as.character(front$Strategy)
wtp <- front$WTP
wtp_range <- range(wtp)
n_wtps <- length(wtp)
# get the indices where the CE strategy isn't the same as the following CE strategy
strat_on_front <- front$Strategy
lagged_strat <- c(strat_on_front[-1], strat_on_front[n_wtps])
switches <- which(strat_on_front != lagged_strat) + 1
n_switches <- length(switches)
# strat_on_front[switches] are the optimal strategies at wtp[switches]
if (n_switches == 0) {
wtp_min <- wtp_range[1]
wtp_max <- wtp_range[2]
one_strat <- unique(front$Strategy)
sum_df <- data.frame(wtp_min,
wtp_max,
one_strat)
} else {
# build up summary data frame
sum_df <- NULL
for (i in 1:n_switches) {
if (i == 1) {
sum_df_row_first <- data.frame(wtp_range[1],
wtp[switches],
strat_on_front[switches - 1],
fix.empty.names = FALSE,
stringsAsFactors = FALSE)
sum_df <- rbind(sum_df, sum_df_row_first)
}
if (i == n_switches) {
sum_df_row_last <- data.frame(wtp[switches],
wtp_range[2],
strat_on_front[switches],
fix.empty.names = FALSE,
stringsAsFactors = FALSE)
sum_df <- rbind(sum_df, sum_df_row_last)
}
if (i > 1) {
sum_df_row_middle <- data.frame(wtp[switches[i]],
wtp[switches[i + 1]],
strat_on_front[switches[i]],
fix.empty.names = FALSE,
stringsAsFactors = FALSE)
sum_df <- rbind(sum_df, sum_df_row_middle)
}
}
}
names(sum_df) <- c("range_min", "range_max", "cost_eff_strat")
sum_df
}
#' Calculate incremental cost-effectiveness ratios (ICERs)
#'
#' @description
#' This function takes in strategies and their associated cost and effect, assigns them
#' one of three statuses (non-dominated, extended dominated, or dominated), and
#' calculates the incremental cost-effectiveness ratios for the non-dominated strategies
#'
#' The cost-effectiveness frontier can be visualized with \code{plot}, which calls \code{\link{plot.icers}}.
#'
#' An efficent way to get from a probabilistic sensitivity analysis to an ICER table
#' is by using \code{summary} on the PSA object and then using its columns as
#' inputs to \code{calculate_icers}.
#'
#' @param cost vector of cost for each strategy
#' @param effect vector of effect for each strategy
#' @param strategies string vector of strategy names
#' With the default (NULL), there is no reference strategy, and the strategies
#' are ranked in ascending order of cost.
#'
#' @return A data frame and \code{icers} object of strategies and their associated
#' status, incremental cost, incremental effect, and ICER.
#'
#' @seealso \code{\link{plot.icers}}
#'
#' @examples
#' ## Base Case
#' # if you have a base case analysis, can use calculate_icers on that
#' data(hund_strat)
#' hund_icers <- calculate_icers(hund_strat$Cost,
#' hund_strat$QALYs,
#' hund_strat$Strategy)
#'
#' plot(hund_icers)
#' # we have so many strategies that we may just want to plot the frontier
#' plot(hund_icers, plot_frontier_only = TRUE)
#' # see ?plot.icers for more options
#'
#' ## Using a PSA object
#' data(psa_cdiff)
#'
#' # summary() gives mean cost and effect for each strategy
#' sum_cdiff <- summary(psa_cdiff)
#'
#' # calculate icers
#' icers <- calculate_icers(sum_cdiff$meanCost,
#' sum_cdiff$meanEffect,
#' sum_cdiff$Strategy)
#' icers
#'
#' # visualize
#' plot(icers)
#'
#' # by default, only the frontier is labeled
#' # if using a small number of strategies, you can label all the points
#' # note that longer strategy names will get truncated
#' plot(icers, label = "all")
#' @export
calculate_icers <- function(cost, effect, strategies) {
# checks on input
n_cost <- length(cost)
n_eff <- length(effect)
n_strat <- length(strategies)
if (n_cost != n_eff | n_eff != n_strat) {
stop("cost, effect, and strategies must all be vectors of the same length", call. = FALSE)
}
# coerce to character, in case they are provided as numeric
char_strat <- as.character(strategies)
# create data frame to hold data
df <- data.frame("Strategy" = char_strat,
"Cost" = cost,
"Effect" = effect,
stringsAsFactors = FALSE)
nstrat <- nrow(df)
# if only one strategy was provided, return df with NAs for incremental
if (nstrat == 1) {
df[, c("ICER", "Inc_Cost", "Inc_Effect")] <- NA
return(df)
}
# three statuses: dominated, extended dominated, and non-dominated
d <- NULL
# detect dominated strategies
# dominated strategies have a higher cost and lower effect
df <- df %>%
arrange(.data$Cost, desc(.data$Effect))
# iterate over strategies and detect (strongly) dominated strategies
# those with higher cost and equal or lower effect
for (i in 1:(nstrat - 1)) {
ith_effect <- df[i, "Effect"]
for (j in (i + 1):nstrat) {
jth_effect <- df[j, "Effect"]
if (jth_effect <= ith_effect) {
# append dominated strategies to vector
d <- c(d, df[j, "Strategy"])
}
}
}
# detect weakly dominated strategies (extended dominance)
# this needs to be repeated until there are no more ED strategies
ed <- vector()
continue <- TRUE # ensure that the loop is run at least once
while (continue) {
# vector of all dominated strategies (strong or weak)
dom <- union(d, ed)
# strategies declared to be non-dominated at this point
nd <- setdiff(strategies, dom)
# compute icers for nd strategies
nd_df <- df[df$Strategy %in% nd, ] %>%
compute_icers()
# number non-d
n_non_d <- nrow(nd_df)
# if only two strategies left, we're done
if (n_non_d <= 2) {
break
}
# strategy identifiers for non-d
nd_strat <- nd_df$Strategy
# now, go through non-d strategies and detect any
# with higher ICER than following strategy
## keep track of whether any ED strategies are picked up
# if not, we're done - exit the loop
new_ed <- 0
for (i in 2:(n_non_d - 1)) {
if (nd_df[i, "ICER"] > nd_df[i + 1, "ICER"]) {
ed <- c(ed, nd_strat[i])
new_ed <- new_ed + 1
}
}
if (new_ed == 0) {
continue <- FALSE
}
}
# recompute icers without weakly dominated strategies
nd_df_icers <- nd_df[!(nd_df$Strategy %in% dom), ] %>%
mutate(Status = "ND") %>%
compute_icers()
# dominated and weakly dominated
d_df <- df[df$Strategy %in% d, ] %>%
mutate(ICER = NA, Status = "D")
ed_df <- df[df$Strategy %in% ed, ] %>%
mutate(ICER = NA, Status = "ED")
# when combining, sort so we have ref,ND,ED,D
results <- bind_rows(d_df, ed_df, nd_df_icers) %>%
arrange(desc(.data$Status), .data$Cost, desc(.data$Effect))
# re-arrange columns
results <- results %>%
select(.data$Strategy, .data$Cost, .data$Effect,
.data$Inc_Cost, .data$Inc_Effect, .data$ICER, .data$Status)
# declare class of results
class(results) <- c("icers", "data.frame")
return(results)
}
#' Calculate incremental cost-effectiveness ratios from a \code{psa} object.
#'
#' @description The mean costs and QALYs for each strategy in a PSA are used
#' to conduct an incremental cost-effectiveness analysis. \code{\link{calculate_icers}} should be used
#' if costs and QALYs for each strategy need to be specified manually, whereas \code{calculate_icers_psa}
#' can be used if mean costs and mean QALYs from the PSA are assumed to represent a base case scenario for
#' calculation of ICERS.
#'
#' Optionally, the \code{uncertainty} argument can be used to provide the 2.5th and 97.5th
#' quantiles for each strategy's cost and QALY outcomes based on the variation present in the PSA.