-
Notifications
You must be signed in to change notification settings - Fork 4
/
class_analysis_dataset.R
4231 lines (3831 loc) · 178 KB
/
class_analysis_dataset.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
## |
## | *Dataset classes*
## |
## | 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: 7962 $
## | Last changed: $Date: 2024-05-31 13:41:37 +0200 (Fr, 31 Mai 2024) $
## | Last changed by: $Author: pahlke $
## |
#' @include f_analysis_utilities.R
#' @include f_core_utilities.R
#' @include f_object_r_code.R
NULL
C_KEY_WORDS_GROUPS <- c("group", "groups")
C_KEY_WORDS_STAGES <- c("stage", "stages")
C_KEY_WORDS_SUBSETS <- c("subset", "subsets")
C_KEY_WORDS_SAMPLE_SIZES <- .getAllParameterNameVariants(c("n", "N", "sampleSizes", "sampleSize"))
C_KEY_WORDS_MEANS <- c("means", "mean")
C_KEY_WORDS_ST_DEVS <- .getAllParameterNameVariants(c("stDevs", "stDev", "stds", "sd"))
C_KEY_WORDS_EVENTS <- c("event", "events")
C_KEY_WORDS_OVERALL_EVENTS <- .getAllParameterNameVariants(c("overallEvents", "overallEvent"))
C_KEY_WORDS_EXPECTED_EVENTS <- .getAllParameterNameVariants(c("expectedEvents", "expectedEvent"))
C_KEY_WORDS_VARIANCE_EVENTS <- .getAllParameterNameVariants(c("varianceEvents", "varianceEvent"))
C_KEY_WORDS_OVERALL_EXPECTED_EVENTS <- .getAllParameterNameVariants(c("overallExpectedEvents", "overallExpectedEvent"))
C_KEY_WORDS_OVERALL_VARIANCE_EVENTS <- .getAllParameterNameVariants(c("overallVarianceEvents", "overallVarianceEvent"))
C_KEY_WORDS_OVERALL_SAMPLE_SIZES <- .getAllParameterNameVariants(c(
"overallN", "overallSampleSizes", "overallSampleSize"
))
C_KEY_WORDS_OVERALL_MEANS <- .getAllParameterNameVariants(c("overallMeans", "overallMean"))
C_KEY_WORDS_OVERALL_ST_DEVS <- .getAllParameterNameVariants(c(
"overallStDevs", "overallStDev", "overall.sd", "overall_sd"
))
C_KEY_WORDS_ALLOCATION_RATIOS <- .getAllParameterNameVariants(c("ar", "allocationRatios", "allocationRatio"))
C_KEY_WORDS_LOG_RANKS <- .getAllParameterNameVariants(c("logRanks", "logRank", "lr"))
C_KEY_WORDS_OVERALL_ALLOCATION_RATIOS <- .getAllParameterNameVariants(c(
"oar", "car", "overallAllocationRatios", "overallAllocationRatio"
))
C_KEY_WORDS_OVERALL_LOG_RANKS <- .getAllParameterNameVariants(c("olr", "clr", "overallLogRanks", "overallLogRank"))
C_KEY_WORDS <- c(
C_KEY_WORDS_GROUPS,
C_KEY_WORDS_STAGES,
C_KEY_WORDS_SUBSETS,
C_KEY_WORDS_SAMPLE_SIZES,
C_KEY_WORDS_MEANS,
C_KEY_WORDS_ST_DEVS,
C_KEY_WORDS_EVENTS,
C_KEY_WORDS_OVERALL_EVENTS,
C_KEY_WORDS_OVERALL_SAMPLE_SIZES,
C_KEY_WORDS_OVERALL_MEANS,
C_KEY_WORDS_OVERALL_ST_DEVS,
C_KEY_WORDS_ALLOCATION_RATIOS,
C_KEY_WORDS_LOG_RANKS,
C_KEY_WORDS_OVERALL_ALLOCATION_RATIOS,
C_KEY_WORDS_OVERALL_LOG_RANKS
)
#' @title
#' Read Dataset
#'
#' @description
#' Reads a data file and returns it as dataset object.
#'
#' @param file A CSV file (see \code{\link[utils]{read.table}}).
#' @param header A logical value indicating whether the file contains the names of
#' the variables as its first line.
#' @param sep The field separator character. Values on each line of the file are separated
#' by this character. If sep = "," (the default for \code{readDataset}) the separator is a comma.
#' @param quote The set of quoting characters. To disable quoting altogether, use
#' quote = "". See scan for the behavior on quotes embedded in quotes. Quoting is only
#' considered for columns read as character, which is all of them unless \code{colClasses} is specified.
#' @param dec The character used in the file for decimal points.
#' @param fill logical. If \code{TRUE} then in case the rows have unequal length, blank fields
#' are implicitly added.
#' @param comment.char character: a character vector of length one containing a single character
#' or an empty string. Use "" to turn off the interpretation of comments altogether.
#' @param fileEncoding character string: if non-empty declares the encoding used on a file
#' (not a connection) so the character data can be re-encoded.
#' See the 'Encoding' section of the help for file, the 'R Data Import/Export Manual' and 'Note'.
#' @param ... Further arguments to be passed to \code{\link[utils]{read.table}}.
#'
#' @details
#' \code{readDataset} is a wrapper function that uses \code{\link[utils]{read.table}} to read the
#' CSV file into a data frame, transfers it from long to wide format with \code{\link[stats]{reshape}}
#' and puts the data to \code{\link[=getDataset]{getDataset()}}.
#'
#' @template return_object_dataset
#'
#' @seealso
#' \itemize{
#' \item \code{\link[=readDatasets]{readDatasets()}} for reading multiple datasets,
#' \item \code{\link[=writeDataset]{writeDataset()}} for writing a single dataset,
#' \item \code{\link[=writeDatasets]{writeDatasets()}} for writing multiple datasets.
#' }
#'
#' @examples
#' \dontrun{
#' dataFileRates <- system.file("extdata",
#' "dataset_rates.csv",
#' package = "rpact"
#' )
#' if (dataFileRates != "") {
#' datasetRates <- readDataset(dataFileRates)
#' datasetRates
#' }
#'
#' dataFileMeansMultiArm <- system.file("extdata",
#' "dataset_means_multi-arm.csv",
#' package = "rpact"
#' )
#' if (dataFileMeansMultiArm != "") {
#' datasetMeansMultiArm <- readDataset(dataFileMeansMultiArm)
#' datasetMeansMultiArm
#' }
#'
#' dataFileRatesMultiArm <- system.file("extdata",
#' "dataset_rates_multi-arm.csv",
#' package = "rpact"
#' )
#' if (dataFileRatesMultiArm != "") {
#' datasetRatesMultiArm <- readDataset(dataFileRatesMultiArm)
#' datasetRatesMultiArm
#' }
#'
#' dataFileSurvivalMultiArm <- system.file("extdata",
#' "dataset_survival_multi-arm.csv",
#' package = "rpact"
#' )
#' if (dataFileSurvivalMultiArm != "") {
#' datasetSurvivalMultiArm <- readDataset(dataFileSurvivalMultiArm)
#' datasetSurvivalMultiArm
#' }
#' }
#'
#' @export
#'
readDataset <- function(file, ..., header = TRUE, sep = ",", quote = "\"",
dec = ".", fill = TRUE, comment.char = "", fileEncoding = "UTF-8") {
if (!file.exists(file)) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "the file '", file, "' does not exist")
}
data <- utils::read.table(
file = file, header = header, sep = sep,
quote = quote, dec = dec, fill = fill, fileEncoding = fileEncoding, ...
)
dataWide <- stats::reshape(data = data, direction = "wide", idvar = "stages", timevar = "groups")
colnames(dataWide) <- gsub("\\.", "", colnames(dataWide))
return(getDataset(dataWide))
}
#' @title
#' Write Dataset
#'
#' @description
#' Writes a dataset to a CSV file.
#'
#' @param dataset A dataset.
#' @param file The target CSV file.
#' @param append Logical. Only relevant if file is a character string.
#' If \code{TRUE}, the output is appended to the file. If \code{FALSE}, any existing file of the name is destroyed.
#' @param sep The field separator character. Values on each line of the file are separated
#' by this character. If sep = "," (the default for \code{writeDataset}) the separator is a comma.
#' @param quote The set of quoting characters. To disable quoting altogether, use
#' quote = "". See scan for the behavior on quotes embedded in quotes. Quoting is only
#' considered for columns read as character, which is all of them unless \code{colClasses} is specified.
#' @param dec The character used in the file for decimal points.
#' @param eol The character(s) to print at the end of each line (row).
#' @param na The string to use for missing values in the data.
#' @param row.names Either a logical value indicating whether the row names of \code{dataset} are
#' to be written along with \code{dataset}, or a character vector of row names to be written.
#' @param col.names Either a logical value indicating whether the column names of \code{dataset} are
#' to be written along with \code{dataset}, or a character vector of column names to be written.
#' See the section on 'CSV files' for the meaning of \code{col.names = NA}.
#' @param qmethod A character string specifying how to deal with embedded double quote characters
#' when quoting strings. Must be one of "double" (default in \code{writeDataset}) or "escape".
#' @param fileEncoding Character string: if non-empty declares the encoding used on a file
#' (not a connection) so the character data can be re-encoded.
#' See the 'Encoding' section of the help for file, the 'R Data Import/Export Manual' and 'Note'.
#' @param ... Further arguments to be passed to \code{\link[utils]{write.table}}.
#'
#' @details
#' \code{\link[=writeDataset]{writeDataset()}} is a wrapper function that coerces the dataset to a data frame and uses \cr
#' \code{\link[utils]{write.table}} to write it to a CSV file.
#'
#' @seealso
#' \itemize{
#' \item \code{\link[=writeDatasets]{writeDatasets()}} for writing multiple datasets,
#' \item \code{\link[=readDataset]{readDataset()}} for reading a single dataset,
#' \item \code{\link[=readDatasets]{readDatasets()}} for reading multiple datasets.
#' }
#'
#' @examples
#' \dontrun{
#' datasetOfRates <- getDataset(
#' n1 = c(11, 13, 12, 13),
#' n2 = c(8, 10, 9, 11),
#' events1 = c(10, 10, 12, 12),
#' events2 = c(3, 5, 5, 6)
#' )
#' writeDataset(datasetOfRates, "dataset_rates.csv")
#' }
#'
#' @export
#'
writeDataset <- function(dataset, file, ..., append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = NA, qmethod = "double",
fileEncoding = "UTF-8") {
.assertIsDataset(dataset)
x <- as.data.frame(dataset, niceColumnNamesEnabled = FALSE)
utils::write.table(
x = x, file = file, append = append, quote = quote, sep = sep,
eol = eol, na = na, dec = dec, row.names = FALSE,
col.names = TRUE, qmethod = qmethod,
fileEncoding = fileEncoding
)
}
#' @title
#' Read Multiple Datasets
#'
#' @description
#' Reads a data file and returns it as a list of dataset objects.
#'
#' @param file A CSV file (see \code{\link[utils]{read.table}}).
#' @param header A logical value indicating whether the file contains the names of
#' the variables as its first line.
#' @param sep The field separator character. Values on each line of the file are separated
#' by this character. If sep = "," (the default for \code{readDatasets}) the separator is a comma.
#' @param quote The set of quoting characters. To disable quoting altogether, use
#' quote = "". See scan for the behavior on quotes embedded in quotes. Quoting is only
#' considered for columns read as character, which is all of them unless \code{colClasses} is specified.
#' @param dec The character used in the file for decimal points.
#' @param fill logical. If \code{TRUE} then in case the rows have unequal length, blank fields
#' are implicitly added.
#' @param comment.char character: a character vector of length one containing a single character
#' or an empty string. Use "" to turn off the interpretation of comments altogether.
#' @param fileEncoding character string: if non-empty declares the encoding used on a file
#' (not a connection) so the character data can be re-encoded.
#' See the 'Encoding' section of the help for file, the 'R Data Import/Export Manual' and 'Note'.
#' @param ... Further arguments to be passed to \code{\link[utils]{read.table}}.
#'
#' @details
#' Reads a file that was written by \code{\link[=writeDatasets]{writeDatasets()}} before.
#'
#' @return Returns a \code{\link[base]{list}} of \code{\link{Dataset}} objects.
#'
#' @seealso
#' \itemize{
#' \item \code{\link[=readDataset]{readDataset()}} for reading a single dataset,
#' \item \code{\link[=writeDatasets]{writeDatasets()}} for writing multiple datasets,
#' \item \code{\link[=writeDataset]{writeDataset()}} for writing a single dataset.
#' }
#'
#' @examples
#' dataFile <- system.file("extdata", "datasets_rates.csv", package = "rpact")
#' if (dataFile != "") {
#' datasets <- readDatasets(dataFile)
#' datasets
#' }
#' @export
#'
readDatasets <- function(file, ..., header = TRUE, sep = ",", quote = "\"",
dec = ".", fill = TRUE, comment.char = "", fileEncoding = "UTF-8") {
if (!file.exists(file)) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "the file '", file, "' does not exist")
}
data <- utils::read.table(
file = file, header = header, sep = sep,
quote = quote, dec = dec, fill = fill, fileEncoding = fileEncoding, ...
)
if (is.null(data[["datasetId"]])) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "data file must contain the column 'datasetId'")
}
datasets <- list()
for (datasetId in unique(data$datasetId)) {
subData <- data[data$datasetId == datasetId, ]
dataFrame <- subset(subData, select = -datasetId)
description <- NA_character_
if (!is.null(dataFrame[["description"]])) {
description <- as.character(dataFrame$description[1])
dataFrame <- subset(dataFrame, select = -description)
}
if (length(unique(subData$groups)) == 2) {
dataWide <- stats::reshape(dataFrame, direction = "wide", idvar = "stages", timevar = "groups")
colnames(dataWide) <- gsub("\\.", "", colnames(dataWide))
dataset <- getDataset(dataWide)
} else {
dataset <- getDataset(dataFrame)
}
dataset$setDescription(description)
datasets <- c(datasets, dataset)
}
return(datasets)
}
#' @title
#' Write Multiple Datasets
#'
#' @description
#' Writes a list of datasets to a CSV file.
#'
#' @param datasets A list of datasets.
#' @param file The target CSV file.
#' @param append Logical. Only relevant if file is a character string.
#' If \code{TRUE}, the output is appended to the file. If FALSE, any existing file of the name is destroyed.
#' @param sep The field separator character. Values on each line of the file are separated
#' by this character. If sep = "," (the default for \code{writeDatasets}) the separator is a comma.
#' @param quote The set of quoting characters. To disable quoting altogether, use
#' quote = "". See scan for the behavior on quotes embedded in quotes. Quoting is only
#' considered for columns read as character, which is all of them unless \code{colClasses} is specified.
#' @param dec The character used in the file for decimal points.
#' @param eol The character(s) to print at the end of each line (row).
#' @param na The string to use for missing values in the data.
#' @param row.names Either a logical value indicating whether the row names of \code{dataset} are
#' to be written along with \code{dataset}, or a character vector of row names to be written.
#' @param col.names Either a logical value indicating whether the column names of \code{dataset} are
#' to be written along with \code{dataset}, or a character vector of column names to be written.
#' See the section on 'CSV files' for the meaning of \code{col.names = NA}.
#' @param qmethod A character string specifying how to deal with embedded double quote characters
#' when quoting strings. Must be one of "double" (default in \code{writeDatasets}) or "escape".
#' @param fileEncoding Character string: if non-empty declares the encoding used on a file
#' (not a connection) so the character data can be re-encoded.
#' See the 'Encoding' section of the help for file, the 'R Data Import/Export Manual' and 'Note'.
#' @param ... Further arguments to be passed to \code{\link[utils]{write.table}}.
#'
#' @details
#' The format of the CSV file is optimized for usage of \code{\link[=readDatasets]{readDatasets()}}.
#'
#' @seealso
#' \itemize{
#' \item \code{\link[=writeDataset]{writeDataset()}} for writing a single dataset,
#' \item \code{\link[=readDatasets]{readDatasets()}} for reading multiple datasets,
#' \item \code{\link[=readDataset]{readDataset()}} for reading a single dataset.
#' }
#'
#' @examples
#' \dontrun{
#' d1 <- getDataset(
#' n1 = c(11, 13, 12, 13),
#' n2 = c(8, 10, 9, 11),
#' events1 = c(10, 10, 12, 12),
#' events2 = c(3, 5, 5, 6)
#' )
#' d2 <- getDataset(
#' n1 = c(9, 13, 12, 13),
#' n2 = c(6, 10, 9, 11),
#' events1 = c(10, 10, 12, 12),
#' events2 = c(4, 5, 5, 6)
#' )
#' datasets <- list(d1, d2)
#' writeDatasets(datasets, "datasets_rates.csv")
#' }
#'
#' @export
#'
writeDatasets <- function(datasets, file, ..., append = FALSE, quote = TRUE, sep = ",",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = NA, qmethod = "double",
fileEncoding = "UTF-8") {
if (!is.list(datasets)) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "'datasets' must be a list of datasets")
}
if (length(datasets) == 0) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "'datasets' is empty")
}
datasetType <- NA_character_
dataFrames <- NULL
for (i in 1:length(datasets)) {
dataset <- datasets[[i]]
.assertIsDataset(dataset)
if (is.na(datasetType)) {
datasetType <- .getClassName(dataset)
} else if (.getClassName(dataset) != datasetType) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "all datasets must have the same type")
}
data <- as.data.frame(dataset, niceColumnNamesEnabled = FALSE)
datasetId <- ifelse(!is.null(dataset$getId()) && !is.na(dataset$getId()), dataset$getId(), i)
data <- cbind(rep(datasetId, nrow(data)), data)
colnames(data)[1] <- "datasetId"
if (!is.null(dataset$getDescription()) && !is.na(dataset$getDescription())) {
data <- cbind(data, rep(dataset$getDescription(), nrow(data)))
colnames(data)[ncol(data)] <- "description"
}
if (is.null(dataFrames)) {
dataFrames <- data
} else {
dataFrames <- rbind(dataFrames, data)
}
}
if (is.null(dataFrames)) {
stop(C_EXCEPTION_TYPE_RUNTIME_ISSUE, "failed to bind datasets")
}
utils::write.table(
x = dataFrames, file = file, append = append, quote = quote, sep = sep,
eol = eol, na = na, dec = dec, row.names = FALSE,
col.names = TRUE, qmethod = qmethod,
fileEncoding = fileEncoding
)
}
.getDataset <- function(..., floatingPointNumbersEnabled = FALSE) {
args <- list(...)
if (length(args) == 0) {
stop(C_EXCEPTION_TYPE_MISSING_ARGUMENT, "data.frame, data vectors, or datasets expected")
}
if (.optionalArgsContainsDatasets(...)) {
if (length(args) == 1) {
return(args[[1]])
}
design <- .getDesignFromArgs(...)
if (length(args) == 2 && !is.null(design)) {
dataset <- .getDatasetFromArgs(...)
if (!is.null(dataset)) {
dataset <- dataset$clone(deep = TRUE)
dataset$.design <- design
return(dataset)
}
}
dataset <- .getEnrichmentDatasetFromArgs(...)
dataset$.design <- design
return(dataset)
}
exampleType <- args[["example"]]
if (!is.null(exampleType) && exampleType %in% c("means", "rates", "survival")) {
return(.getDatasetExample(exampleType = exampleType))
}
if (length(args) == 1 && !is.null(args[[1]]) && is.list(args[[1]]) && !is.data.frame(args[[1]])) {
return(.getDatasetMeansFromModelsByStage(emmeansResults = args[[1]]))
}
emmeansResults <- .getDatasetMeansModelObjectsList(args)
if (!is.null(emmeansResults) && length(emmeansResults) > 0) {
return(.getDatasetMeansFromModelsByStage(emmeansResults = emmeansResults))
}
dataFrame <- .getDataFrameFromArgs(...)
design <- .getDesignFromArgs(...)
if (is.null(dataFrame)) {
args <- .removeDesignFromArgs(args)
paramNames <- names(args)
paramNames <- paramNames[paramNames != ""]
numberOfParameters <- length(args)
if (numberOfParameters > 0 && names(args)[1] == "" && .isTrialDesign(args[[1]])) {
numberOfParameters <- numberOfParameters - 1
}
if (length(paramNames) != numberOfParameters) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "all parameters must be named")
}
if (length(paramNames) != length(unique(paramNames))) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "the parameter names must be unique")
}
dataFrame <- .createDataFrame(...)
}
enrichmentEnabled <- .isDataObjectEnrichment(...)
if (.isDataObjectMeans(...)) {
return(DatasetMeans$new(
dataFrame = dataFrame,
floatingPointNumbersEnabled = floatingPointNumbersEnabled,
enrichmentEnabled = enrichmentEnabled,
.design = design
))
}
if (.isDataObjectRates(...)) {
return(DatasetRates$new(
dataFrame = dataFrame,
floatingPointNumbersEnabled = floatingPointNumbersEnabled,
enrichmentEnabled = enrichmentEnabled,
.design = design
))
}
if (.isDataObjectNonStratifiedEnrichmentSurvival(...)) {
return(DatasetEnrichmentSurvival$new(
dataFrame = dataFrame,
floatingPointNumbersEnabled = floatingPointNumbersEnabled,
enrichmentEnabled = enrichmentEnabled,
.design = design
))
}
if (.isDataObjectSurvival(...)) {
return(DatasetSurvival$new(
dataFrame = dataFrame,
floatingPointNumbersEnabled = floatingPointNumbersEnabled,
enrichmentEnabled = enrichmentEnabled,
.design = design
))
}
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "failed to identify dataset type")
}
#' @title
#' Get Dataset
#'
#' @description
#' Creates a dataset object and returns it.
#'
#' @param ... A \code{data.frame} or some data vectors defining the dataset.
#' @param floatingPointNumbersEnabled If \code{TRUE},
#' sample sizes and event numbers can be specified as floating-point numbers
#' (this make sense, e.g., for theoretical comparisons); \cr
#' by default \code{floatingPointNumbersEnabled = FALSE}, i.e.,
#' samples sizes and event numbers defined as floating-point numbers will be truncated.
#'
#' @details
#' The different dataset types \code{DatasetMeans}, of \code{DatasetRates}, or
#' \code{DatasetSurvival} can be created as follows:
#' \itemize{
#' \item An element of \code{\link{DatasetMeans}} for one sample is created by \cr
#' \code{getDataset(sampleSizes =, means =, stDevs =)} where \cr
#' \code{sampleSizes}, \code{means}, \code{stDevs} are vectors with stage-wise sample sizes,
#' means and standard deviations of length given by the number of available stages.
#' \item An element of \code{\link{DatasetMeans}} for two samples is created by \cr
#' \code{getDataset(sampleSizes1 =, sampleSizes2 =, means1 =, means2 =, } \cr
#' \code{stDevs1 =, stDevs2 =)} where
#' \code{sampleSizes1}, \code{sampleSizes2}, \code{means1}, \code{means2},
#' \code{stDevs1}, \code{stDevs2} are vectors with
#' stage-wise sample sizes, means and standard deviations for the two treatment groups
#' of length given by the number of available stages.
#' \item An element of \code{\link{DatasetRates}} for one sample is created by \cr
#' \code{getDataset(sampleSizes =, events =)} where \code{sampleSizes}, \code{events} are vectors
#' with stage-wise sample sizes and events of length given by the number of available stages.
#' \item An element of \code{\link{DatasetRates}} for two samples is created by \cr
#' \code{getDataset(sampleSizes1 =, sampleSizes2 =, events1 =, events2 =)} where
#' \code{sampleSizes1}, \code{sampleSizes2}, \code{events1}, \code{events2}
#' are vectors with stage-wise sample sizes
#' and events for the two treatment groups of length given by the number of available stages.
#' \item An element of \code{\link{DatasetSurvival}} is created by \cr
#' \code{getDataset(events =, logRanks =, allocationRatios =)} where
#' \code{events}, \code{logRanks}, and \code{allocation ratios} are the stage-wise events,
#' (one-sided) logrank statistics, and allocation ratios.
#' \item An element of \code{\link{DatasetMeans}}, \code{\link{DatasetRates}}, and \code{\link{DatasetSurvival}}
#' for more than one comparison is created by adding subsequent digits to the variable names.
#' The system can analyze these data in a multi-arm many-to-one comparison setting where the
#' group with the highest index represents the control group.
#' }
#' Prefix \code{overall[Capital case of first letter of variable name]...} for the variable
#' names enables entering the overall (cumulative) results and calculates stage-wise statistics.
#' Since rpact version 3.2, the prefix \code{cumulative[Capital case of first letter of variable name]...} or
#' \code{cum[Capital case of first letter of variable name]...} can alternatively be used for this.
#'
#' \code{n} can be used in place of \code{samplesizes}.
#'
#' Note that in survival design usually the overall (cumulative) events and logrank test statistics are provided
#' in the output, so \cr
#' \code{getDataset(cumulativeEvents=, cumulativeLogRanks =, cumulativeAllocationRatios =)} \cr
#' is the usual command for entering survival data. Note also that for \code{cumulativeLogranks} also the
#' z scores from a Cox regression can be used.
#'
#' For multi-arm designs, the index refers to the considered comparison. For example,\cr
#' \code{
#' getDataset(events1=c(13, 33), logRanks1 = c(1.23, 1.55), events2 = c(16, NA), logRanks2 = c(1.55, NA))
#' } \cr
#' refers to the case where one active arm (1) is considered at both stages whereas active arm 2
#' was dropped at interim. Number of events and logrank statistics are entered for the corresponding
#' comparison to control (see Examples).
#'
#' For enrichment designs, the comparison of two samples is provided for an unstratified
#' (sub-population wise) or stratified data input.\cr
#' For non-stratified (sub-population wise) data input the data sets are defined for the sub-populations
#' S1, S2, ..., F, where F refers to the full populations. Use of \code{getDataset(S1 = , S2, ..., F = )}
#' defines the data set to be used in \code{\link[=getAnalysisResults]{getAnalysisResults()}} (see examples)\cr
#' For stratified data input the data sets are defined for the strata S1, S12, S2, ..., R, where R
#' refers to the remainder of the strata such that the union of all sets is the full population.
#' Use of \code{getDataset(S1 = , S12 = , S2, ..., R = )} defines the data set to be used in
#' \code{\link[=getAnalysisResults]{getAnalysisResults()}} (see examples)\cr
#' For survival data, for enrichment designs the log-rank statistics can only be entered as stratified
#' log-rank statistics in order to provide strong control of Type I error rate. For stratified data input,
#' the variables to be specified in \code{getDataset()} are \code{cumEvents}, \code{cumExpectedEvents},
#' \code{cumVarianceEvents}, and \code{cumAllocationRatios} or \code{overallEvents}, \code{overallExpectedEvents},
#' \code{overallVarianceEvents}, and \code{overallAllocationRatios}. From this, (stratified) log-rank tests and
#' and the independent increments are calculated.
#'
#' @template return_object_dataset
#'
#' @template examples_get_dataset
#'
#' @include f_analysis_base.R
#' @include f_analysis_utilities.R
#'
#' @export
#'
getDataset <- function(..., floatingPointNumbersEnabled = FALSE) {
dataset <- .getDataset(floatingPointNumbersEnabled = floatingPointNumbersEnabled, ...)
if (dataset$.enrichmentEnabled && dataset$getNumberOfGroups() != 2) {
warning("Only population enrichment data with 2 groups can be analyzed but ",
dataset$getNumberOfGroups(), " group",
ifelse(dataset$getNumberOfGroups() == 1, " is", "s are"), " defined",
call. = FALSE
)
}
return(dataset)
}
#' @rdname getDataset
#' @export
getDataSet <- function(..., floatingPointNumbersEnabled = FALSE) {
return(getDataset(floatingPointNumbersEnabled = floatingPointNumbersEnabled, ...))
}
.getDatasetMeansModelObjectsList <- function(args) {
if (is.null(args) || length(args) == 0 || !is.list(args)) {
return(NULL)
}
emmeansResults <- list()
for (arg in args) {
if (inherits(arg, "emmGrid")) {
emmeansResults[[length(emmeansResults) + 1]] <- arg
}
}
if (length(emmeansResults) == 0) {
return(NULL)
}
argNames <- names(args)
for (i in 1:length(args)) {
arg <- args[[i]]
if (!inherits(arg, "emmGrid")) {
argName <- argNames[i]
argInfo <- ""
if (length(argName) == 1 && argName != "") {
argInfo <- paste0(sQuote(argName), " ")
}
argInfo <- paste0(argInfo, "(", .arrayToString(arg), ")")
warning("Argument ", argInfo, " will be ignored because only 'emmGrid' objects will be respected")
}
}
return(emmeansResults)
}
.getStandardDeviationFromStandardError <- function(sampleSize, standardError, ...,
dfValue = NA_real_, alpha = 0.05, lmEnabled = TRUE, stDevCalcMode = "auto") {
qtCalcEnablbled <- length(stDevCalcMode) == 1 && !is.na(stDevCalcMode) && stDevCalcMode == "t"
if ((qtCalcEnablbled || !lmEnabled) && !is.na(dfValue) && !is.infinite(dfValue) && dfValue > 0) {
qValue <- stats::qt(1 - alpha / 2, df = dfValue)
stDev <- standardError * 2 / qValue * sqrt(sampleSize)
} else {
stDev <- standardError * sqrt(sampleSize)
}
return(stDev)
}
.getDatasetMeansFromModelsByStage <- function(emmeansResults, correctGroupOrder = TRUE) {
if (is.null(emmeansResults)) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, sQuote(emmeansResults), " must be a non-empty list")
}
if (!is.list(emmeansResults)) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, sQuote(emmeansResults), " must be a list")
}
if (length(emmeansResults) == 0) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, sQuote(emmeansResults), " must be not empty")
}
for (stage in 1:length(emmeansResults)) {
if (!inherits(emmeansResults[[stage]], "emmGrid")) {
stop(sprintf(
paste0(
"%s%s must contain %s objects created by emmeans(x), ",
"where x is a linear model result (one object per stage; class is %s at stage %s)"
),
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, sQuote("emmeansResults"), sQuote("emmGrid"),
.getClassName(emmeansResults[[stage]]), stage
))
}
}
stages <- integer(0)
groups <- integer(0)
means <- numeric(0)
stDevs <- numeric(0)
sampleSizes <- numeric(0)
lmEnabled <- TRUE
tryCatch(
{
modelCall <- emmeansResults[[1]]@model.info$call
modelFunction <- as.character(modelCall)[1]
lmEnabled <- modelFunction == "lm"
if (!grepl(paste0("::", modelFunction), modelFunction)) {
packageName <- .getPackageName(modelFunction)
if (!is.na(packageName)) {
modelFunction <- paste0(packageName, "::", modelFunction)
}
}
if (lmEnabled) {
warning("When using ", modelFunction, "() ",
"the estimated marginal means and standard deviations can be inaccurate ",
"and analysis results based on this values may be imprecise",
call. = FALSE
)
} else {
warning("Using ", modelFunction, " emmeans result objects as ",
"arguments of getDataset() is experminental in this rpact version and not fully validated",
call. = FALSE
)
}
},
error = function(e) {
warning("Using emmeans result objects as ",
"arguments of getDataset() is experminental in this rpact version and not fully validated",
call. = FALSE
)
}
)
stDevCalcMode <- getOption("rpact.dataset.stdev.calc.mode", "auto") # auto, sigma, norm, t
for (stage in 1:length(emmeansResults)) {
emmeansResult <- emmeansResults[[stage]]
emmeansResultsSummary <- summary(emmeansResult)
emmeansResultsList <- as.list(emmeansResult)
if (is.null(emmeansResultsSummary[["emmean"]])) {
stop(
C_EXCEPTION_TYPE_RUNTIME_ISSUE,
"the objects in summary(emmeansResults) must contain the field 'emmean'"
)
}
for (expectedField in c("sigma", "extras")) {
if (is.null(emmeansResultsList[[expectedField]])) {
stop(
C_EXCEPTION_TYPE_RUNTIME_ISSUE,
"the objects in as.list(emmeansResults) must contain the field ", sQuote(expectedField)
)
}
}
numberOfGroups <- length(emmeansResultsSummary$emmean)
rpactGroupNumbers <- 1:numberOfGroups
if (correctGroupOrder) {
rpactGroupNumbers <- 1
if (numberOfGroups > 1) {
rpactGroupNumbers <- c(2:numberOfGroups, rpactGroupNumbers)
}
}
for (group in 1:length(emmeansResultsSummary$emmean)) {
stages <- c(stages, stage)
groups <- c(groups, group)
rpactGroupNumber <- rpactGroupNumbers[group]
standardError <- emmeansResultsSummary$SE[rpactGroupNumber]
sampleSize <- emmeansResultsList$extras[rpactGroupNumber, ]
meanValue <- emmeansResultsSummary$emmean[rpactGroupNumber]
dfValue <- emmeansResultsSummary$df[rpactGroupNumber]
if (length(stDevCalcMode) == 1 && !is.na(stDevCalcMode) && stDevCalcMode == "sigma") {
# pooled standard deviation from emmeans
stDev <- emmeansResultsList$sigma
} else {
stDev <- .getStandardDeviationFromStandardError(sampleSize, standardError,
dfValue = dfValue, lmEnabled = lmEnabled, stDevCalcMode = stDevCalcMode
)
}
means <- c(means, meanValue)
stDevs <- c(stDevs, stDev)
sampleSizes <- c(sampleSizes, sampleSize)
}
}
data <- data.frame(
stages = stages,
groups = groups,
means = means,
stDevs = stDevs,
sampleSizes = sampleSizes
)
data <- data[order(data$stages, data$groups), ]
dataWide <- stats::reshape(data = data, direction = "wide", idvar = "stages", timevar = "groups")
colnames(dataWide) <- gsub("\\.", "", colnames(dataWide))
return(getDataset(dataWide))
}
.optionalArgsContainsDatasets <- function(...) {
args <- list(...)
if (length(args) == 0) {
return(FALSE)
}
for (arg in args) {
if (inherits(arg, "Dataset")) {
return(TRUE)
}
}
return(FALSE)
}
.getSubsetsFromArgs <- function(...) {
args <- list(...)
if (length(args) == 0) {
stop(C_EXCEPTION_TYPE_MISSING_ARGUMENT, "one or more subset datasets expected")
}
subsetNames <- names(args)
if (is.null(subsetNames)) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "all subsets must be named")
}
if (!("R" %in% subsetNames) && !("F" %in% subsetNames)) {
stop(
C_EXCEPTION_TYPE_MISSING_ARGUMENT,
'"R" (stratified analysis)" or "F" (non-stratified analysis) must be defined as subset'
)
}
subsetNumbers <- gsub("\\D", "", subsetNames)
subsetNumbers <- subsetNumbers[subsetNumbers != ""] # & nchar(subsetNumbers) == 1
if (length(subsetNumbers) == 0) {
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "all subset names (",
.arrayToString(subsetNames), ") must be \"S[n]\", \"R\", or \"F\", ",
"where [n] is a number with increasing digits (starting with 1)"
)
}
stratifiedInput <- "R" %in% subsetNames
subsetNumbers <- paste0(subsetNumbers, collapse = "")
subsetNumbers <- strsplit(subsetNumbers, "")[[1]]
subsetNumbers <- as.integer(subsetNumbers)
gMax <- max(subsetNumbers) + 1
validSubsetNames <- .createSubsetsByGMax(gMax, stratifiedInput = stratifiedInput, all = FALSE)
for (i in 1:length(subsetNames)) {
subsetName <- subsetNames[i]
if (subsetName == "" && !inherits(args[[i]], "TrialDesign")) {
stop(C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "all subsets must be named")
}
if (subsetName != "" && !(subsetName %in% validSubsetNames)) {
suffix <- ifelse(stratifiedInput, " (stratified analysis)", " (non-stratified analysis)")
if (length(validSubsetNames) < 10) {
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "invalid subset name (", subsetName, "); ",
"valid names are ", .arrayToString(validSubsetNames), suffix
)
} else {
restFull <- ifelse(stratifiedInput, '"R"', '"F"')
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT, "invalid subset name (", subsetName, "): ",
"all subset names must be \"S[n]\" or ", restFull, ", ",
"where [n] is a number with increasing digits", suffix
)
}
}
}
subsetNames <- subsetNames[subsetNames != ""]
subsets <- NULL
subsetType <- NA_character_
emptySubsetNames <- validSubsetNames[!(validSubsetNames %in% subsetNames)]
for (subsetName in subsetNames) {
subset <- args[[subsetName]]
if (is.null(subset) || (!.isResultObjectBaseClass(subset) && is.na(subset))) {
emptySubsetNames <- c(emptySubsetNames, subsetName)
} else {
if (!.isDataset(subset)) {
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT,
"subset ", subsetName, " is not a dataset (is ", .getClassName(subset), ")"
)
}
if (!is.na(subsetType) && subsetType != .getClassName(subset)) {
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT,
"all subsets must have the same type (found ", subsetType, " and ", .getClassName(subset), ")"
)
}
subsetType <- .getClassName(subset)
if (is.null(subset[[".data"]])) {
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT,
"subset ", subsetName, " does not contain field '.data'"
)
}
subset <- subset$.data
subset$subset <- rep(subsetName, nrow(subset))
if (is.null(subsets)) {
subsets <- subset
} else {
subsets <- rbind(subsets, subset)
}
}
}
if (length(emptySubsetNames) > 0) {
emptySubsetNames <- unique(emptySubsetNames)
template <- subsets[subsets$subset == ifelse(stratifiedInput, "R", "F"), ]
colNames <- colnames(template)
colNames <- colNames[!(colNames %in% c("stage", "group", "subset"))]
for (colName in colNames) {
template[[colName]] <- rep(NA_real_, nrow(template))
}
for (subsetName in emptySubsetNames) {
template$subset <- rep(subsetName, nrow(template))
subsets <- rbind(subsets, template)
}
if (length(emptySubsetNames) == 1) {
warning("The undefined subset ", emptySubsetNames,
" was defined as empty subset",
call. = FALSE
)
} else {
warning(gettextf(
"The %s undefined subsets %s were defined as empty subsets",
length(emptySubsetNames), .arrayToString(emptySubsetNames)
), call. = FALSE)
}
}
return(subsets)
}
.validateEnrichmentDataFrameAtFirstStage <- function(dataFrame, params) {
dataFrameStage1 <- dataFrame[dataFrame$stage == 1, ]
for (param in params) {
paramValue <- dataFrameStage1[[param]]
if (any(is.null(paramValue) || any(is.infinite(paramValue)))) {
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT,
gettextf(
"all %s values (%s) at first stage must be valid",
sQuote(param), .arrayToString(paramValue, maxLength = 10)
)
)
}
if (any(is.na(paramValue))) {
subsets <- unique(dataFrame$subset)
for (s in subsets) {
subData <- dataFrame[dataFrame$subset == s, ]
subsetParamValues <- subData[[param]]
if (!all(is.na(subsetParamValues)) && any(is.na(subsetParamValues[subData$stage == 1]))) {
stop(
C_EXCEPTION_TYPE_ILLEGAL_ARGUMENT,
gettextf(
"all %s values (%s) at first stage must be valid (NA is not allowed)",