-
Notifications
You must be signed in to change notification settings - Fork 4
/
f_analysis_base.R
2343 lines (2145 loc) · 99.5 KB
/
f_analysis_base.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
## |
## | *Analysis functions*
## |
## | This file is part of the R package rpact:
## | Confirmatory Adaptive Clinical Trial Design and Analysis
## |
## | Author: Gernot Wassmer, PhD, and Friedrich Pahlke, PhD
## | Licensed under "GNU Lesser General Public License" version 3
## | License text can be found here: https://www.r-project.org/Licenses/LGPL-3
## |
## | RPACT company website: https://www.rpact.com
## | rpact package website: https://www.rpact.org
## |
## | Contact us for information about our services: info@rpact.com
## |
## | File version: $Revision: 7808 $
## | Last changed: $Date: 2024-04-05 18:22:34 +0200 (Fr, 05 Apr 2024) $
## | Last changed by: $Author: pahlke $
## |
#' @include f_core_utilities.R
#' @include f_logger.R
#' @include f_object_r_code.R
NULL
.getDesignAndDataInput <- function(..., design, dataInput) {
if (missing(design) && missing(dataInput)) {
stop(C_EXCEPTION_TYPE_MISSING_ARGUMENT, sQuote("dataInput"), " must be specified")
}
if (missing(dataInput) && !missing(design) && inherits(design, "Dataset")) {
dataInput <- design
if (!is.null(dataInput$.design) && inherits(dataInput$.design, "TrialDesign")) {
design <- dataInput$.design
} else {
design <- .getDefaultDesign(..., type = "analysis")
}
} else if (!missing(dataInput) && missing(design)) {
if (!is.null(dataInput$.design) && inherits(dataInput$.design, "TrialDesign")) {
design <- dataInput$.design
} else {
design <- .getDefaultDesign(..., type = "analysis")
}
} else {
.warnInCaseOfTwoSidedPowerArgument(...)
}
.assertIsTrialDesign(design)
.assertIsDataset(dataInput)
return(list(
design = design,
dataInput = dataInput$clone(deep = TRUE)
))
}
#' @title
#' Get Analysis Results
#'
#' @description
#' Calculates and returns the analysis results for the specified design and data.
#'
#' @inheritParams param_design
#' @inheritParams param_dataInput
#' @inheritParams param_directionUpper
#' @inheritParams param_thetaH0
#' @inheritParams param_nPlanned
#' @inheritParams param_allocationRatioPlanned
#' @inheritParams param_stage
#' @inheritParams param_maxInformation
#' @inheritParams param_informationEpsilon
#' @param ... Further arguments to be passed to methods (cf., separate functions in "See Also" below), e.g.,
#' \describe{
#' \item{\code{thetaH1} and \code{stDevH1} (or \code{assumedStDev} / \code{assumedStDevs}),
#' \code{pi1}, \code{pi2}, or \code{piTreatments}, \code{piControl(s)}}{
#' The assumed effect size, standard deviation or rates to calculate the conditional power if \code{nPlanned}
#' is specified. For survival designs, \code{thetaH1} refers to the hazard ratio.
#' For one-armed trials with binary outcome, only \code{pi1} can be specified, for two-armed trials with binary outcome,
#' \code{pi1} and \code{pi2} can be specified referring to the assumed treatment and control rate, respectively.
#' In multi-armed or enrichment designs, you can
#' specify a value or a vector with elements referring to the treatment arms or the sub-populations,
#' respectively. For testing rates, the parameters to be specified are \code{piTreatments} and \code{piControl}
#' (multi-arm designs) and \code{piTreatments} and \code{piControls} (enrichment designs).\cr
#' If not specified, the conditional power is calculated under the assumption of observed effect sizes,
#' standard deviations, rates, or hazard ratios.}
#' \item{\code{iterations}}{Iterations for simulating the power for Fisher's combination test.
#' If the power for more than one remaining stages is to be determined for
#' Fisher's combination test, it is estimated via simulation with specified \cr
#' \code{iterations}, the default is \code{1000}.}
#' \item{\code{seed}}{Seed for simulating the conditional power for Fisher's combination test.
#' See above, default is a random seed.}
#' \item{\code{normalApproximation}}{The type of computation of the p-values. Default is \code{FALSE} for
#' testing means (i.e., the t test is used) and \code{TRUE} for testing rates and the hazard ratio.
#' For testing rates, if \code{normalApproximation = FALSE} is specified, the binomial test
#' (one sample) or the exact test of Fisher (two samples) is used for calculating the p-values.
#' In the survival setting, \code{normalApproximation = FALSE} has no effect.}
#' \item{\code{equalVariances}}{The type of t test. For testing means in two treatment groups, either
#' the t test assuming that the variances are equal or the t test without assuming this,
#' i.e., the test of Welch-Satterthwaite is calculated, default is \code{TRUE}.}
#' \item{\code{intersectionTest}}{Defines the multiple test for the intersection
#' hypotheses in the closed system of hypotheses when testing multiple hypotheses.
#' Five options are available in multi-arm designs: \code{"Dunnett"}, \code{"Bonferroni"}, \code{"Simes"},
#' \code{"Sidak"}, and \code{"Hierarchical"}, default is \code{"Dunnett"}.
#' Four options are available in population enrichment designs: \code{"SpiessensDebois"} (one subset only),
#' \code{"Bonferroni"}, \code{"Simes"}, and \code{"Sidak"}, default is \code{"Simes"}.}
#' \item{\code{varianceOption}}{Defines the way to calculate the variance in multiple treatment arms (> 2)
#' or population enrichment designs for testing means. For multiple arms, three options are available:
#' \code{"overallPooled"}, \code{"pairwisePooled"}, and \code{"notPooled"}, default is \code{"overallPooled"}.
#' For enrichment designs, the options are: \code{"pooled"}, \code{"pooledFromFull"} (one subset only),
#' and \code{"notPooled"}, default is \code{"pooled"}.}
#' \item{\code{stratifiedAnalysis}}{For enrichment designs, typically a stratified analysis should be chosen.
#' For testing means and rates, also a non-stratified analysis based on overall data can be performed.
#' For survival data, only a stratified analysis is possible (see Brannath et al., 2009), default is \code{TRUE}.}
#' }
#'
#' @details
#' Given a design and a dataset, at given stage the function calculates the test results
#' (effect sizes, stage-wise test statistics and p-values, overall p-values and test statistics,
#' conditional rejection probability (CRP), conditional power, Repeated Confidence Intervals (RCIs),
#' repeated overall p-values, and final stage p-values, median unbiased effect estimates,
#' and final confidence intervals.
#'
#' For designs with more than two treatments arms (multi-arm designs) or enrichment designs
#' a closed combination test is performed.
#' That is, additionally the statistics to be used in a closed testing procedure are provided.
#'
#' The conditional power is calculated if the planned sample size for the subsequent stages (\code{nPlanned})
#' is specified. The conditional power is calculated either under the assumption of the observed effect or
#' under the assumption of an assumed effect, that has to be specified (see above).\cr
#' For testing rates in a two-armed trial, pi1 and pi2 typically refer to the rates in the treatment
#' and the control group, respectively. This is not mandatory, however, and so pi1 and pi2 can be interchanged.
#' In many-to-one multi-armed trials, piTreatments and piControl refer to the rates in the treatment arms and
#' the one control arm, and so they cannot be interchanged. piTreatments and piControls in enrichment designs
#' can principally be interchanged, but we use the plural form to indicate that the rates can be differently
#' specified for the sub-populations.
#'
#' Median unbiased effect estimates and confidence intervals are calculated if
#' a group sequential design or an inverse normal combination test design was chosen, i.e., it is not applicable
#' for Fisher's p-value combination test design.
#' For the inverse normal combination test design with more than two stages, a warning informs that the validity
#' of the confidence interval is theoretically shown only if no sample size change was performed.
#'
#' A final stage p-value for Fisher's combination test is calculated only if a two-stage design was chosen.
#' For Fisher's combination test, the conditional power for more than one remaining stages is estimated via simulation.
#'
#' Final stage p-values, median unbiased effect estimates, and final confidence intervals are not calculated
#' for multi-arm and enrichment designs.
#'
#' @return Returns an \code{\link{AnalysisResults}} object.
#' The following generics (R generic functions) are available for this result object:
#' \itemize{
#' \item \code{\link[=names.AnalysisResults]{names}} to obtain the field names,
#' \item \code{\link[=print.ParameterSet]{print()}} to print the object,
#' \item \code{\link[=summary.AnalysisResults]{summary()}} to display a summary of the object,
#' \item \code{\link[=plot.AnalysisResults]{plot()}} to plot the object,
#' \item \code{\link[=as.data.frame.AnalysisResults]{as.data.frame()}} to coerce the object to a \code{\link[base]{data.frame}},
#' \item \code{\link[=as.matrix.FieldSet]{as.matrix()}} to coerce the object to a \code{\link[base]{matrix}}.
#' }
#' @template how_to_get_help_for_generics
#'
#' @seealso
#' \code{\link[=getObservedInformationRates]{getObservedInformationRates()}}
#'
#' @family analysis functions
#'
#' @template examples_get_analysis_results
#'
#' @export
#'
getAnalysisResults <- function(design, dataInput, ...,
directionUpper = TRUE, # C_DIRECTION_UPPER_DEFAULT
thetaH0 = NA_real_,
nPlanned = NA_real_,
allocationRatioPlanned = 1, # C_ALLOCATION_RATIO_DEFAULT
stage = NA_integer_,
maxInformation = NULL,
informationEpsilon = NULL) {
designAndDataInput <- .getDesignAndDataInput(design = design, dataInput = dataInput, ...)
design <- designAndDataInput$design
dataInput <- designAndDataInput$dataInput
repeatedPValues <- NULL
informationRatesRecalculated <- FALSE
if (.isAlphaSpendingDesign(design) && (design$typeBetaSpending == "none") &&
.isTrialDesignGroupSequential(design) && !.isMultiArmDataset(dataInput)) {
observedInformationRates <- NULL
absoluteInformations <- NULL
status <- NULL
if (!is.null(maxInformation) && !is.na(maxInformation)) {
showObservedInformationRatesMessage <- .getOptionalArgument(
"showObservedInformationRatesMessage",
optionalArgumentDefaultValue = TRUE, ...
)
observedInformation <- getObservedInformationRates(
dataInput,
maxInformation = maxInformation,
informationEpsilon = informationEpsilon, stage = stage,
showObservedInformationRatesMessage = showObservedInformationRatesMessage
)
observedInformationRates <- observedInformation$informationRates
absoluteInformations <- observedInformation$absoluteInformations
status <- observedInformation$status
} else if (!is.null(informationEpsilon) && !is.na(informationEpsilon)) {
warning("'informationEpsilon' (", .arrayToString(informationEpsilon),
") will be ignored because 'maxInformation' is undefined",
call. = FALSE
)
}
if (!is.null(observedInformationRates)) {
stageFromData <- dataInput$getNumberOfStages()
if (!is.null(status) && status %in% c("under-running", "over-running") &&
length(observedInformationRates) > 1) {
if (stageFromData == 1) {
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT,
"Recalculation of the information rates not possible at stage 1"
)
}
if (!(getLogLevel() %in% c(C_LOG_LEVEL_DISABLED, C_LOG_LEVEL_PROGRESS))) {
message(
"Calculate alpha values that have actually been spent ",
"at earlier interim analyses at stage ", (stageFromData - 1)
)
}
.assertIsSingleInteger(stage, "stage", naAllowed = TRUE, validateType = FALSE)
observedInformationRatesBefore <- getObservedInformationRates(
dataInput,
maxInformation = maxInformation,
informationEpsilon = informationEpsilon,
stage = ifelse(!is.na(stage), stage - 1, stageFromData - 1),
showObservedInformationRatesMessage = FALSE
)$informationRates
if (length(observedInformationRatesBefore) < length(design$informationRates)) {
for (i in (length(observedInformationRatesBefore) + 1):length(design$informationRates)) {
if (observedInformationRatesBefore[length(observedInformationRatesBefore)] < 1) {
observedInformationRatesBefore <- c(observedInformationRatesBefore, design$informationRates[i])
}
}
}
designBefore <- eval(parse(text = getObjectRCode(design,
newArgumentValues = list(
informationRates = observedInformationRatesBefore
),
stringWrapParagraphWidth = NULL
)))
if (is.na(stage) || stage == stageFromData) {
repeatedPValues <- getAnalysisResults(
design = designBefore,
dataInput = dataInput,
directionUpper = directionUpper,
thetaH0 = thetaH0,
nPlanned = nPlanned,
allocationRatioPlanned = allocationRatioPlanned,
stage = stageFromData - 1,
maxInformation = maxInformation,
informationEpsilon = informationEpsilon,
showObservedInformationRatesMessage = FALSE
)$repeatedPValues
}
userAlphaSpending <- designBefore$alphaSpent
message(
"Use alpha values that have actually been spent at earlier stages ",
"and spend all remaining alpha at the final analysis, ",
"i.e., userAlphaSpending = (",
.arrayToString(userAlphaSpending, digits = 6), ") "
)
observedInformationRates <- getObservedInformationRates(
dataInput,
maxInformation = absoluteInformations[stageFromData],
informationEpsilon = informationEpsilon,
stage = stage,
showObservedInformationRatesMessage = FALSE
)$informationRates
design <- eval(parse(text = getObjectRCode(design,
newArgumentValues = list(
informationRates = observedInformationRates,
userAlphaSpending = userAlphaSpending,
typeOfDesign = C_TYPE_OF_DESIGN_AS_USER
),
stringWrapParagraphWidth = NULL
)))
options("rpact.analyis.repeated.p.values.warnings.enabled" = "FALSE")
warning("Repeated p-values not available for automatic recalculation of boundaries at final stage",
call. = FALSE
)
} else {
design <- eval(parse(text = getObjectRCode(design,
newArgumentValues = list(informationRates = observedInformationRates),
stringWrapParagraphWidth = NULL
)))
}
informationRatesRecalculated <- TRUE
}
} else {
if (!is.null(maxInformation) && !is.na(maxInformation)) {
warning("'maxInformation' (", .arrayToString(maxInformation),
") will be ignored because it is only applicable for alpha spending", "\n",
"group sequential designs with no or fixed futility bounds and a single hypothesis",
call. = FALSE
)
}
if (!is.null(informationEpsilon) && !is.na(informationEpsilon)) {
warning("'informationEpsilon' (", .arrayToString(informationEpsilon),
") will be ignored because it is only applicable for alpha spending", "\n",
"group sequential designs with no or fixed futility bounds and a single hypothesis",
call. = FALSE
)
}
}
result <- NULL
if (.isEnrichmentDataset(dataInput)) {
result <- .getAnalysisResultsEnrichment(
design = design, dataInput = dataInput,
directionUpper = directionUpper,
thetaH0 = thetaH0,
nPlanned = nPlanned,
allocationRatioPlanned = allocationRatioPlanned,
stage = stage, ...
)
} else if (.isMultiArmDataset(dataInput)) {
result <- .getAnalysisResultsMultiArm(
design = design, dataInput = dataInput,
directionUpper = directionUpper,
thetaH0 = thetaH0,
nPlanned = nPlanned,
allocationRatioPlanned = allocationRatioPlanned,
stage = stage, ...
)
} else {
stage <- .getStageFromOptionalArguments(...,
dataInput = dataInput,
design = design, stage = stage, showWarnings = TRUE
)
.assertIsValidDirectionUpper(directionUpper, sided = design$sided)
.assertIsValidDataInput(dataInput = dataInput, design = design, stage = stage)
on.exit(dataInput$.trim())
.assertIsValidThetaH0DataInput(thetaH0, dataInput)
if (is.null(maxInformation) || is.na(maxInformation)) {
.assertAreSuitableInformationRates(design, dataInput, stage = stage)
}
.assertIsValidNPlanned(nPlanned, design$kMax, stage, required = FALSE)
.assertIsValidAllocationRatioPlanned(allocationRatioPlanned,
numberOfGroups = dataInput$getNumberOfGroups()
)
if (dataInput$isDatasetMeans()) {
if (is.na(thetaH0)) {
thetaH0 <- C_THETA_H0_MEANS_DEFAULT
}
result <- .getAnalysisResultsMeans(
design = design, dataInput = dataInput,
directionUpper = directionUpper, thetaH0 = thetaH0, nPlanned = nPlanned,
allocationRatioPlanned = allocationRatioPlanned, stage = stage, ...
)
} else if (dataInput$isDatasetRates()) {
if (is.na(thetaH0)) {
thetaH0 <- C_THETA_H0_RATES_DEFAULT
}
result <- .getAnalysisResultsRates(
design = design, dataInput = dataInput,
directionUpper = directionUpper, thetaH0 = thetaH0, nPlanned = nPlanned,
allocationRatioPlanned = allocationRatioPlanned, stage = stage, ...
)
} else if (dataInput$isDatasetSurvival()) {
if (is.na(thetaH0)) {
thetaH0 <- C_THETA_H0_SURVIVAL_DEFAULT
}
result <- .getAnalysisResultsSurvival(
design = design, dataInput = dataInput,
directionUpper = directionUpper, thetaH0 = thetaH0, nPlanned = nPlanned,
allocationRatioPlanned = allocationRatioPlanned, stage = stage, ...
)
}
if (is.null(result)) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "'dataInput' type '", .getClassName(dataInput), "' is not implemented yet")
}
if (informationRatesRecalculated) {
result$maxInformation <- as.integer(maxInformation)
result$.setParameterType("maxInformation", C_PARAM_USER_DEFINED)
if (!is.null(informationEpsilon) && !is.na(informationEpsilon)) {
result$informationEpsilon <- informationEpsilon
result$.setParameterType("informationEpsilon", C_PARAM_USER_DEFINED)
}
}
}
if (!is.null(result) && !is.null(repeatedPValues)) {
result$repeatedPValues <- repeatedPValues
}
if (design$kMax > 1 && .isTrialDesignInverseNormalOrGroupSequential(design) &&
design$typeOfDesign %in% c(C_TYPE_OF_DESIGN_AS_USER, C_TYPE_OF_DESIGN_NO_EARLY_EFFICACY)) {
indices <- design$userAlphaSpending == 0
if (.isEnrichmentDataset(dataInput) || .isMultiArmDataset(dataInput)) {
result$repeatedConfidenceIntervalLowerBounds[, indices] <- NA_real_
result$repeatedConfidenceIntervalUpperBounds[, indices] <- NA_real_
result$repeatedPValues[, indices] <- NA_real_
} else {
result$repeatedConfidenceIntervalLowerBounds[indices] <- NA_real_
result$repeatedConfidenceIntervalUpperBounds[indices] <- NA_real_
result$repeatedPValues[indices] <- NA_real_
}
}
options("rpact.analyis.repeated.p.values.warnings.enabled" = "TRUE")
return(result)
}
#' @title
#' Get Stage Results
#'
#' @description
#' Returns summary statistics and p-values for a given data set and a given design.
#'
#' @inheritParams param_design
#' @inheritParams param_dataInput
#' @inheritParams param_stage
#' @param ... Further (optional) arguments to be passed:
#' \describe{
#' \item{\code{thetaH0}}{The null hypothesis value,
#' default is \code{0} for the normal and the binary case (testing means and rates, respectively),
#' it is \code{1} for the survival case (testing the hazard ratio).\cr\cr
#' For non-inferiority designs, \code{thetaH0} is the non-inferiority bound.
#' That is, in case of (one-sided) testing of
#' \itemize{
#' \item \emph{means}: a value \code{!= 0}
#' (or a value \code{!= 1} for testing the mean ratio) can be specified.
#' \item \emph{rates}: a value \code{!= 0}
#' (or a value \code{!= 1} for testing the risk ratio \code{pi1 / pi2}) can be specified.
#' \item \emph{survival data}: a bound for testing H0:
#' \code{hazard ratio = thetaH0 != 1} can be specified.
#' }
#' For testing a rate in one sample, a value \code{thetaH0} in (0, 1) has to be specified for
#' defining the null hypothesis H0: \code{pi = thetaH0}.}
#' \item{\code{normalApproximation}}{The
#' type of computation of the p-values. Default is \code{FALSE} for
#' testing means (i.e., the t test is used) and \code{TRUE} for testing rates and the hazard ratio.
#' For testing rates, if \code{normalApproximation = FALSE} is specified, the binomial test
#' (one sample) or the exact test of Fisher (two samples) is used for calculating the p-values.
#' In the survival setting, \code{normalApproximation = FALSE} has no effect.}
#' \item{\code{equalVariances}}{The type of t test. For testing means in two treatment groups, either
#' the t test assuming that the variances are equal or the t test without assuming this,
#' i.e., the test of Welch-Satterthwaite is calculated, default is \code{TRUE}.}
#' \item{\code{directionUpper}}{The direction of one-sided testing.
#' Default is \code{TRUE} which means that larger values of the
#' test statistics yield smaller p-values.}
#' \item{\code{intersectionTest}}{Defines the multiple test for the intersection
#' hypotheses in the closed system of hypotheses when testing multiple hypotheses.
#' Five options are available in multi-arm designs: \code{"Dunnett"}, \code{"Bonferroni"}, \code{"Simes"},
#' \code{"Sidak"}, and \code{"Hierarchical"}, default is \code{"Dunnett"}.
#' Four options are available in population enrichment designs: \code{"SpiessensDebois"} (one subset only),
#' \code{"Bonferroni"}, \code{"Simes"}, and \code{"Sidak"}, default is \code{"Simes"}.}
#' \item{\code{varianceOption}}{Defines the way to calculate the variance in multiple treatment arms (> 2)
#' or population enrichment designs for testing means. For multiple arms, three options are available:
#' \code{"overallPooled"}, \code{"pairwisePooled"}, and \code{"notPooled"}, default is \code{"overallPooled"}.
#' For enrichment designs, the options are: \code{"pooled"}, \code{"pooledFromFull"} (one subset only),
#' and \code{"notPooled"}, default is \code{"pooled"}.}
#' \item{\code{stratifiedAnalysis}}{For enrichment designs, typically a stratified analysis should be chosen.
#' For testing means and rates, also a non-stratified analysis based on overall data can be performed.
#' For survival data, only a stratified analysis is possible (see Brannath et al., 2009), default is \code{TRUE}.}
#' }
#'
#' @details
#' Calculates and returns the stage results of the specified design and data input at the specified stage.
#'
#' @return Returns a \code{\link{StageResults}} object.
#' \itemize{
#' \item \code{\link[=names.StageResults]{names}} to obtain the field names,
#' \item \code{\link[=print.FieldSet]{print()}} to print the object,
#' \item \code{\link[=summary.ParameterSet]{summary()}} to display a summary of the object,
#' \item \code{\link[=plot.StageResults]{plot()}} to plot the object,
#' \item \code{\link[=as.data.frame.StageResults]{as.data.frame()}} to coerce the object to a \code{\link[base]{data.frame}},
#' \item \code{\link[=as.matrix.FieldSet]{as.matrix()}} to coerce the object to a \code{\link[base]{matrix}}.
#' }
#' @template how_to_get_help_for_generics
#'
#' @family analysis functions
#'
#' @template examples_get_stage_results
#'
#' @export
#'
getStageResults <- function(design, dataInput, ..., stage = NA_integer_) {
designAndDataInput <- .getDesignAndDataInput(design = design, dataInput = dataInput, ...)
design <- designAndDataInput$design
dataInput <- designAndDataInput$dataInput
if (.isEnrichmentDataset(dataInput)) {
return(.getStageResultsEnrichment(
design = design, dataInput = dataInput, stage = stage, ...
))
} else if (.isMultiArmDataset(dataInput)) {
return(.getStageResultsMultiArm(
design = design, dataInput = dataInput, stage = stage, ...
))
} else {
stage <- .getStageFromOptionalArguments(..., dataInput = dataInput, design = design, stage = stage)
.assertIsValidDataInput(dataInput = dataInput, design = design, stage = stage)
on.exit(dataInput$.trim())
if (dataInput$isDatasetMeans()) {
return(.getStageResultsMeans(
design = design, dataInput = dataInput, stage = stage,
userFunctionCallEnabled = TRUE, ...
))
}
if (dataInput$isDatasetRates()) {
return(.getStageResultsRates(
design = design, dataInput = dataInput, stage = stage,
userFunctionCallEnabled = TRUE, ...
))
}
if (dataInput$isDatasetSurvival()) {
return(.getStageResultsSurvival(
design = design, dataInput = dataInput, stage = stage,
userFunctionCallEnabled = TRUE, ...
))
}
}
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "'dataInput' type '", .getClassName(dataInput), "' is not supported")
}
.getStageFromOptionalArguments <- function(..., dataInput, design, showWarnings = FALSE) {
.assertIsTrialDesign(design)
stage <- .getOptionalArgument("stage", ...)
if (!is.null(stage) && !is.na(stage)) {
.assertIsValidStage(stage, design$kMax)
if (showWarnings) {
.assertIsDataset(dataInput)
if (stage > dataInput$getNumberOfStages()) {
warning("'stage' (", stage, ") will be ignored because 'dataInput' ",
"has only ", dataInput$getNumberOfStages(), " stages defined",
call. = FALSE
)
}
}
return(as.integer(stage))
}
.assertIsDataset(dataInput)
stage <- dataInput$getNumberOfStages()
stage <- min(stage, design$kMax)
stage <- as.integer(stage)
.assertIsValidStage(stage, design$kMax)
return(stage)
}
#'
#' @title
#' Get Test Actions
#'
#' @description
#' Returns test actions.
#'
#' @inheritParams param_stageResults
#' @param ... Only available for backward compatibility.
#'
#' @details
#' Returns the test actions of the specified design and stage results at the specified stage.
#'
#' @return Returns a \code{\link[base]{character}} vector of length \code{kMax}
#' Returns a \code{\link[base]{numeric}} vector of length \code{kMax}containing the test actions of each stage.
#'
#' @family analysis functions
#'
#' @template examples_get_test_actions
#'
#' @export
#'
getTestActions <- function(stageResults, ...) {
.warnInCaseOfUnknownArguments(functionName = "getTestActions", ...)
stageResults <- .getStageResultsObject(stageResults, functionName = "getTestActions", ...)
.assertIsStageResultsNonMultiHypotheses(stageResults)
design <- stageResults$.design
testActions <- rep(NA_character_, design$kMax)
if (.isTrialDesignInverseNormal(design)) {
for (k in 1:stageResults$stage) {
if (design$sided == 1) {
if (k < design$kMax) {
if (stageResults$combInverseNormal[k] > design$criticalValues[k]) {
testActions[k] <- "reject and stop"
} else if (stageResults$combInverseNormal[k] < design$futilityBounds[k]) {
testActions[k] <- "accept and stop"
} else {
testActions[k] <- "continue"
}
} else {
if (stageResults$combInverseNormal[k] > design$criticalValues[k]) {
testActions[k] <- "reject"
} else {
testActions[k] <- "accept"
}
}
}
if (design$sided == 2) {
if (k < design$kMax) {
if (abs(stageResults$combInverseNormal[k]) > design$criticalValues[k]) {
testActions[k] <- "reject and stop"
} else {
testActions[k] <- "continue"
}
} else {
if (abs(stageResults$combInverseNormal[k]) > design$criticalValues[k]) {
testActions[k] <- "reject"
} else {
testActions[k] <- "accept"
}
}
}
}
} else if (.isTrialDesignGroupSequential(design)) {
for (k in 1:stageResults$stage) {
if (design$sided == 1) {
if (k < design$kMax) {
if (.getOneMinusQNorm(stageResults$overallPValues[k]) > design$criticalValues[k]) {
testActions[k] <- "reject and stop"
} else if (.getOneMinusQNorm(stageResults$overallPValues[k]) < design$futilityBounds[k]) {
testActions[k] <- "accept and stop"
} else {
testActions[k] <- "continue"
}
} else {
if (.getOneMinusQNorm(stageResults$overallPValues[k]) > design$criticalValues[k]) {
testActions[k] <- "reject"
} else {
testActions[k] <- "accept"
}
}
}
if (design$sided == 2) {
if (k < design$kMax) {
if (abs(.getOneMinusQNorm(stageResults$overallPValues[k])) > design$criticalValues[k]) {
testActions[k] <- "reject and stop"
} else {
testActions[k] <- "continue"
}
} else {
if (abs(.getOneMinusQNorm(stageResults$overallPValues[k])) > design$criticalValues[k]) {
testActions[k] <- "reject"
} else {
testActions[k] <- "accept"
}
}
}
}
} else if (.isTrialDesignFisher(design)) {
for (k in 1:stageResults$stage) {
if (design$sided == 1) {
if (k < design$kMax) {
if (stageResults$combFisher[k] < design$criticalValues[k]) {
testActions[k] <- "reject and stop"
} else if (stageResults$pValues[k] > design$alpha0Vec[k]) {
testActions[k] <- "accept and stop"
} else {
testActions[k] <- "continue"
}
} else {
if (stageResults$combFisher[k] < design$criticalValues[k]) {
testActions[k] <- "reject"
} else {
testActions[k] <- "accept"
}
}
}
if (design$sided == 2) {
if (k < design$kMax) {
if (min(stageResults$combFisher[k], 1 - stageResults$combFisher[k]) < design$criticalValues[k]) {
testActions[k] <- "reject and stop"
} else {
testActions[k] <- "continue"
}
} else {
if (min(stageResults$combFisher[k], 1 - stageResults$combFisher[k]) < design$criticalValues[k]) {
testActions[k] <- "reject"
} else {
testActions[k] <- "accept"
}
}
}
}
}
return(testActions)
}
#'
#' @title
#' Get Repeated Confidence Intervals
#'
#' @description
#' Calculates and returns the lower and upper limit of the repeated confidence intervals of the trial.
#'
#' @inheritParams param_design
#' @inheritParams param_dataInput
#' @inheritParams param_directionUpper
#' @inheritParams param_tolerance
#' @inheritParams param_stage
#' @param ... Further arguments to be passed to methods (cf., separate functions in "See Also" below), e.g.,
#' \describe{
#' \item{\code{normalApproximation}}{The type of computation of the p-values. Default is \code{FALSE} for
#' testing means (i.e., the t test is used) and \code{TRUE} for testing rates and the hazard ratio.
#' For testing rates, if \code{normalApproximation = FALSE} is specified, the binomial test
#' (one sample) or the exact test of Fisher (two samples) is used for calculating the p-values.
#' In the survival setting, \code{normalApproximation = FALSE} has no effect.}
#' \item{\code{equalVariances}}{The type of t test. For testing means in two treatment groups, either
#' the t test assuming that the variances are equal or the t test without assuming this,
#' i.e., the test of Welch-Satterthwaite is calculated, default is \code{TRUE}.}
#' \item{\code{intersectionTest}}{Defines the multiple test for the intersection
#' hypotheses in the closed system of hypotheses when testing multiple hypotheses.
#' Five options are available in multi-arm designs: \code{"Dunnett"}, \code{"Bonferroni"}, \code{"Simes"},
#' \code{"Sidak"}, and \code{"Hierarchical"}, default is \code{"Dunnett"}.
#' Four options are available in population enrichment designs: \code{"SpiessensDebois"} (one subset only),
#' \code{"Bonferroni"}, \code{"Simes"}, and \code{"Sidak"}, default is \code{"Simes"}.}
#' \item{\code{varianceOption}}{Defines the way to calculate the variance in multiple treatment arms (> 2)
#' or population enrichment designs for testing means. For multiple arms, three options are available:
#' \code{"overallPooled"}, \code{"pairwisePooled"}, and \code{"notPooled"}, default is \code{"overallPooled"}.
#' For enrichment designs, the options are: \code{"pooled"}, \code{"pooledFromFull"} (one subset only),
#' and \code{"notPooled"}, default is \code{"pooled"}.}
#' \item{\code{stratifiedAnalysis}}{For enrichment designs, typically a stratified analysis should be chosen.
#' For testing means and rates, also a non-stratified analysis based on overall data can be performed.
#' For survival data, only a stratified analysis is possible (see Brannath et al., 2009), default is \code{TRUE}.}
#' }
#'
#' @details
#' The repeated confidence interval at a given stage of the trial contains the
#' parameter values that are not rejected using the specified sequential design.
#' It can be calculated at each stage of the trial and can thus be used as a monitoring tool.
#'
#' The repeated confidence intervals are provided up to the specified stage.
#'
#' @return Returns a \code{\link[base]{matrix}} with \code{2} rows
#' and \code{kMax} columns containing the lower RCI limits in the first row and
#' the upper RCI limits in the second row, where each column represents a stage.
#'
#' @family analysis functions
#'
#' @template examples_get_repeated_confidence_intervals
#'
#' @export
#'
getRepeatedConfidenceIntervals <- function(design, dataInput, ...,
directionUpper = TRUE, # C_DIRECTION_UPPER_DEFAULT
tolerance = 1e-06, # C_ANALYSIS_TOLERANCE_DEFAULT
stage = NA_integer_) {
.assertIsValidTolerance(tolerance)
designAndDataInput <- .getDesignAndDataInput(design = design, dataInput = dataInput, ...)
design <- designAndDataInput$design
dataInput <- designAndDataInput$dataInput
if (.isEnrichmentDataset(dataInput)) {
return(.getRepeatedConfidenceIntervalsEnrichment(
design = design, dataInput = dataInput, stage = stage, ...
))
}
if (.isMultiArmDataset(dataInput)) {
return(.getRepeatedConfidenceIntervalsMultiArm(
design = design, dataInput = dataInput, stage = stage, ...
))
}
stage <- .getStageFromOptionalArguments(..., dataInput = dataInput, design = design, stage = stage)
.assertIsValidDataInput(dataInput = dataInput, design = design, stage = stage)
on.exit(dataInput$.trim())
if (dataInput$isDatasetMeans()) {
return(.getRepeatedConfidenceIntervalsMeans(
design = design, dataInput = dataInput, directionUpper = directionUpper,
tolerance = tolerance, stage = stage, ...
))
}
if (dataInput$isDatasetRates()) {
return(.getRepeatedConfidenceIntervalsRates(
design = design, dataInput = dataInput, directionUpper = directionUpper,
tolerance = tolerance, stage = stage, ...
))
}
if (dataInput$isDatasetSurvival()) {
return(.getRepeatedConfidenceIntervalsSurvival(
design = design, dataInput = dataInput, directionUpper = directionUpper,
tolerance = tolerance, stage = stage, ...
))
}
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "'dataInput' type '", .getClassName(dataInput), "' is not implemented yet")
}
.getStageResultsObject <- function(stageResults, ..., functionName) {
if (missing(stageResults)) {
stop(C_EXCEPTION_TYPE_MISSING_ARGUMENT, "'stageResults' must be defined")
}
.stopInCaseOfIllegalStageDefinition(stageResults, ...)
args <- list(...)
if (.isTrialDesign(stageResults)) {
if (length(args) == 0) {
stop(C_EXCEPTION_TYPE_MISSING_ARGUMENT, "'stageResults' must be defined")
}
stageResults <- args[[1]]
.logDebug(
"The separate specification of the design in ", functionName, "() is deprecated ",
"because the 'stageResults' object contains the design already"
)
}
if (.isDataset(stageResults)) {
stageResults <- getStageResults(dataInput = stageResults, ...)
}
if (!.isStageResults(stageResults)) {
for (arg in args) {
if (.isStageResults(arg)) {
return(arg)
}
}
stop(C_EXCEPTION_TYPE_MISSING_ARGUMENT, "'stageResults' must be defined")
}
return(stageResults)
}
#'
#' @title
#' Get Conditional Power
#'
#' @description
#' Calculates and returns the conditional power.
#'
#' @inheritParams param_stageResults
#' @inheritParams param_nPlanned
#' @inheritParams param_allocationRatioPlanned
#' @param ... Further (optional) arguments to be passed:
#' \describe{
#' \item{\code{thetaH1} and \code{stDevH1} (or \code{assumedStDev} / \code{assumedStDevs}),
#' \code{pi1}, \code{pi2}, or \code{piTreatments}, \code{piControl(s)}}{
#' The assumed effect size, standard deviation or rates to calculate the conditional power if \code{nPlanned}
#' is specified. For survival designs, \code{thetaH1} refers to the hazard ratio.
#' For one-armed trials with binary outcome, only \code{pi1} can be specified, for two-armed trials with binary outcome,
#' \code{pi1} and \code{pi2} can be specified referring to the assumed treatment and control rate, respectively.
#' In multi-armed or enrichment designs, you can
#' specify a value or a vector with elements referring to the treatment arms or the sub-populations,
#' respectively. For testing rates, the parameters to be specified are \code{piTreatments} and \code{piControl} (multi-arm
#' designs) and \code{piTreatments} and \code{piControls} (enrichment designs).\cr
#' If not specified, the conditional power is calculated under the assumption of observed effect sizes,
#' standard deviations, rates, or hazard ratios.}
#' \item{\code{iterations}}{Iterations for simulating the power for Fisher's combination test.
#' If the power for more than one remaining stages is to be determined for
#' Fisher's combination test, it is estimated via simulation with specified \cr
#' \code{iterations}, the default is \code{1000}.}
#' \item{\code{seed}}{Seed for simulating the conditional power for Fisher's combination test.
#' See above, default is a random seed.}
#' }
#'
#' @details
#' The conditional power is calculated if the planned sample size for the subsequent stages is specified.\cr
#' For testing rates in a two-armed trial, pi1 and pi2 typically refer to the rates in the treatment
#' and the control group, respectively. This is not mandatory, however, and so pi1 and pi2 can be interchanged.
#' In many-to-one multi-armed trials, piTreatments and piControl refer to the rates in the treatment arms and
#' the one control arm, and so they cannot be interchanged. piTreatments and piControls in enrichment designs
#' can principally be interchanged, but we use the plural form to indicate that the rates can be differently
#' specified for the sub-populations.
#'
#' For Fisher's combination test, the conditional power for more than one remaining stages is
#' estimated via simulation.
#'
#' @seealso
#' \code{\link[=plot.StageResults]{plot.StageResults()}} or \code{\link[=plot.AnalysisResults]{plot.AnalysisResults()}}
#' for plotting the conditional power.
#'
#' @return Returns a \code{\link{ConditionalPowerResults}} object.
#' The following generics (R generic functions) are available for this result object:
#' \itemize{
#' \item \code{\link[=names.FieldSet]{names()}} to obtain the field names,
#' \item \code{\link[=print.FieldSet]{print()}} to print the object,
#' \item \code{\link[=summary.ParameterSet]{summary()}} to display a summary of the object,
#' \item \code{\link[=plot.ParameterSet]{plot()}} to plot the object,
#' \item \code{\link[=as.data.frame.ParameterSet]{as.data.frame()}} to coerce the object to a \code{\link[base]{data.frame}},
#' \item \code{\link[=as.matrix.FieldSet]{as.matrix()}} to coerce the object to a \code{\link[base]{matrix}}.
#' }
#' @template how_to_get_help_for_generics
#'
#' @family analysis functions
#'
#' @template examples_get_conditional_power
#'
#' @export
#'
getConditionalPower <- function(stageResults, ..., nPlanned,
allocationRatioPlanned = 1 # C_ALLOCATION_RATIO_DEFAULT
) {
# .stopInCaseOfIllegalStageDefinition(stageResults, ...)
stageResults <- .getStageResultsObject(stageResults = stageResults, functionName = "getConditionalPower", ...)
.assertIsValidAllocationRatioPlanned(allocationRatioPlanned, stageResults$.dataInput$getNumberOfGroups())
conditionalPower <- NULL
if (.isEnrichmentStageResults(stageResults)) {
conditionalPower <- .getConditionalPowerEnrichment(
stageResults = stageResults,
nPlanned = nPlanned, allocationRatioPlanned = allocationRatioPlanned, ...
)
} else if (.isMultiArmStageResults(stageResults)) {
conditionalPower <- .getConditionalPowerMultiArm(
stageResults = stageResults,
nPlanned = nPlanned, allocationRatioPlanned = allocationRatioPlanned, ...
)
} else {
.assertIsStageResults(stageResults)
if (stageResults$isDatasetMeans()) {
conditionalPower <- .getConditionalPowerMeans(
stageResults = stageResults,
nPlanned = nPlanned, allocationRatioPlanned = allocationRatioPlanned, ...
)
} else if (stageResults$isDatasetRates()) {
conditionalPower <- .getConditionalPowerRates(
stageResults = stageResults,
nPlanned = nPlanned, allocationRatioPlanned = allocationRatioPlanned, ...
)
} else if (stageResults$isDatasetSurvival()) {
conditionalPower <- .getConditionalPowerSurvival(
stageResults = stageResults,
nPlanned = nPlanned, allocationRatioPlanned = allocationRatioPlanned, ...
)
}
}
if (!is.null(conditionalPower)) {
addPlotData <- .getOptionalArgument("addPlotData", ...)
if (!is.null(addPlotData) && isTRUE(addPlotData)) {
conditionalPower$.plotData <- .getConditionalPowerPlot(
stageResults = stageResults, nPlanned = nPlanned,
allocationRatioPlanned = allocationRatioPlanned, ...
)
}
conditionalPower$.setParameterType("nPlanned", C_PARAM_USER_DEFINED)
conditionalPower$.setParameterType(
"allocationRatioPlanned",
ifelse(allocationRatioPlanned == C_ALLOCATION_RATIO_DEFAULT,
C_PARAM_DEFAULT_VALUE, C_PARAM_USER_DEFINED
)
)
return(conditionalPower)
} else {
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "'dataInput' type '",
.getClassName(stageResults$.dataInput), "' is not implemented yet"
)
}
}
.getConditionalPowerPlot <- function(...,
stageResults, nPlanned, allocationRatioPlanned = NA_real_) {
if (.isMultiArmStageResults(stageResults)) {
return(.getConditionalPowerPlotMultiArm(
stageResults = stageResults,
nPlanned = nPlanned, allocationRatioPlanned = allocationRatioPlanned, ...
))
}
if (.isEnrichmentStageResults(stageResults)) {
return(.getConditionalPowerPlotEnrichment(
stageResults = stageResults,
nPlanned = nPlanned, allocationRatioPlanned = allocationRatioPlanned, ...
))
}
.assertIsStageResults(stageResults)
.stopInCaseOfIllegalStageDefinition2(...)
stage <- stageResults$stage
if (stage == stageResults$.design$kMax && length(nPlanned) > 0) {
stage <- stageResults$.design$kMax - 1
}
.assertIsValidNPlanned(nPlanned, stageResults$.design$kMax, stage)
if (is.na(allocationRatioPlanned)) {
allocationRatioPlanned <- C_ALLOCATION_RATIO_DEFAULT
}
if (stageResults$isDatasetMeans()) {