-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathcolby_constructors.R
2035 lines (1944 loc) · 61.1 KB
/
colby_constructors.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
label_pos_values <- c("hidden", "visible", "topleft")
#' @name internal_methods
#' @rdname int_methods
NULL
#' Combine `SplitVector` objects
#'
#' @param x (`SplitVector`)\cr a `SplitVector` object.
#' @param ... splits or `SplitVector` objects.
#'
#' @return Various, but should be considered implementation details.
#'
#' @rdname int_methods
#' @exportMethod c
setMethod("c", "SplitVector", function(x, ...) {
arglst <- list(...)
stopifnot(all(sapply(arglst, is, "Split")))
tmp <- c(unclass(x), arglst)
SplitVector(lst = tmp)
})
## split_rows and split_cols are "recursive method stacks" which follow
## the general pattern of accept object -> call add_*_split on slot of object ->
## update object with value returned from slot method, return object.
##
## Thus each of the methods is idempotent, returning an updated object of the
## same class it was passed. The exception for idempotency is the NULL method
## which constructs a PreDataTableLayouts object with the specified split in the
## correct place.
## The cascading (by class) in this case is as follows for the row case:
## PreDataTableLayouts -> PreDataRowLayout -> SplitVector
#' @param cmpnd_fun (`function`)\cr intended for internal use.
#' @param pos (`numeric(1)`)\cr intended for internal use.
#' @param spl (`Split`)\cr the split.
#'
#' @rdname int_methods
setGeneric(
"split_rows",
function(lyt = NULL, spl, pos,
cmpnd_fun = AnalyzeMultiVars) {
standardGeneric("split_rows")
}
)
#' @rdname int_methods
setMethod("split_rows", "NULL", function(lyt, spl, pos, cmpnd_fun = AnalyzeMultiVars) {
.Deprecated(msg = "Initializing layouts via NULL is deprecated, please use basic_table() instead")
rl <- PreDataRowLayout(SplitVector(spl))
cl <- PreDataColLayout()
PreDataTableLayouts(rlayout = rl, clayout = cl)
})
#' @rdname int_methods
setMethod(
"split_rows", "PreDataRowLayout",
function(lyt, spl, pos, cmpnd_fun = AnalyzeMultiVars) {
stopifnot(pos > 0 && pos <= length(lyt) + 1)
tmp <- if (pos <= length(lyt)) {
split_rows(lyt[[pos]], spl, pos, cmpnd_fun)
} else {
if (pos != 1 && has_force_pag(spl)) {
stop("page_by splits cannot have top-level siblings",
call. = FALSE
)
}
SplitVector(spl)
}
lyt[[pos]] <- tmp
lyt
}
)
is_analysis_spl <- function(spl) {
is(spl, "VAnalyzeSplit") || is(spl, "AnalyzeMultiVars")
}
## note "pos" is ignored here because it is for which nest-chain
## spl should be placed in, NOIT for where in that chain it should go
#' @rdname int_methods
setMethod(
"split_rows", "SplitVector",
function(lyt, spl, pos, cmpnd_fun = AnalyzeMultiVars) {
## if(is_analysis_spl(spl) &&
## is_analysis_spl(last_rowsplit(lyt))) {
## return(cmpnd_last_rowsplit(lyt, spl, cmpnd_fun))
## }
if (has_force_pag(spl) && length(lyt) > 0 && !has_force_pag(lyt[[length(lyt)]])) {
stop("page_by splits cannot be nested within non-page_by splits",
call. = FALSE
)
}
tmp <- c(unclass(lyt), spl)
SplitVector(lst = tmp)
}
)
#' @rdname int_methods
setMethod(
"split_rows", "PreDataTableLayouts",
function(lyt, spl, pos) {
rlyt <- rlayout(lyt)
addtl <- FALSE
split_label <- obj_label(spl)
if (
is(spl, "Split") && ## exclude existing tables that are being tacked in
identical(label_position(spl), "topleft") &&
length(split_label) == 1 && nzchar(split_label)
) {
addtl <- TRUE
## label_position(spl) <- "hidden"
}
rlyt <- split_rows(rlyt, spl, pos)
rlayout(lyt) <- rlyt
if (addtl) {
lyt <- append_topleft(lyt, indent_string(split_label, .tl_indent(lyt)))
}
lyt
}
)
#' @rdname int_methods
setMethod(
"split_rows", "ANY",
function(lyt, spl, pos) {
stop("nope. can't add a row split to that (", class(lyt), "). contact the maintaner.")
}
)
## cmpnd_last_rowsplit =====
#' @rdname int_methods
#'
#' @param constructor (`function`)\cr constructor function.
setGeneric("cmpnd_last_rowsplit", function(lyt, spl, constructor) standardGeneric("cmpnd_last_rowsplit"))
#' @rdname int_methods
setMethod("cmpnd_last_rowsplit", "NULL", function(lyt, spl, constructor) {
stop("no existing splits to compound with. contact the maintainer") # nocov
})
#' @rdname int_methods
setMethod(
"cmpnd_last_rowsplit", "PreDataRowLayout",
function(lyt, spl, constructor) {
pos <- length(lyt)
tmp <- cmpnd_last_rowsplit(lyt[[pos]], spl, constructor)
lyt[[pos]] <- tmp
lyt
}
)
#' @rdname int_methods
setMethod(
"cmpnd_last_rowsplit", "SplitVector",
function(lyt, spl, constructor) {
pos <- length(lyt)
lst <- lyt[[pos]]
tmp <- if (is(lst, "CompoundSplit")) {
spl_payload(lst) <- c(
.uncompound(spl_payload(lst)),
.uncompound(spl)
)
obj_name(lst) <- make_ma_name(spl = lst)
lst
## XXX never reached because AnalzyeMultiVars inherits from
## CompoundSplit???
} else {
constructor(.payload = list(lst, spl))
}
lyt[[pos]] <- tmp
lyt
}
)
#' @rdname int_methods
setMethod(
"cmpnd_last_rowsplit", "PreDataTableLayouts",
function(lyt, spl, constructor) {
rlyt <- rlayout(lyt)
rlyt <- cmpnd_last_rowsplit(rlyt, spl, constructor)
rlayout(lyt) <- rlyt
lyt
}
)
#' @rdname int_methods
setMethod(
"cmpnd_last_rowsplit", "ANY",
function(lyt, spl, constructor) {
stop(
"nope. can't do cmpnd_last_rowsplit to that (",
class(lyt), "). contact the maintaner."
)
}
)
## split_cols ====
#' @rdname int_methods
setGeneric(
"split_cols",
function(lyt = NULL, spl, pos) {
standardGeneric("split_cols")
}
)
#' @rdname int_methods
setMethod("split_cols", "NULL", function(lyt, spl, pos) {
.Deprecated(msg = paste(
"Initializing layouts via NULL is deprecated,",
"please use basic_table() instead"
))
cl <- PreDataColLayout(SplitVector(spl))
rl <- PreDataRowLayout()
PreDataTableLayouts(rlayout = rl, clayout = cl)
})
#' @rdname int_methods
setMethod(
"split_cols", "PreDataColLayout",
function(lyt, spl, pos) {
stopifnot(pos > 0 && pos <= length(lyt) + 1)
tmp <- if (pos <= length(lyt)) {
split_cols(lyt[[pos]], spl, pos)
} else {
SplitVector(spl)
}
lyt[[pos]] <- tmp
lyt
}
)
#' @rdname int_methods
setMethod(
"split_cols", "SplitVector",
function(lyt, spl, pos) {
tmp <- c(lyt, spl)
SplitVector(lst = tmp)
}
)
#' @rdname int_methods
setMethod(
"split_cols", "PreDataTableLayouts",
function(lyt, spl, pos) {
rlyt <- lyt@col_layout
rlyt <- split_cols(rlyt, spl, pos)
lyt@col_layout <- rlyt
lyt
}
)
#' @rdname int_methods
setMethod(
"split_cols", "ANY",
function(lyt, spl, pos) {
stop(
"nope. can't add a col split to that (", class(lyt),
"). contact the maintaner."
)
}
)
# Constructors =====
## Pipe-able functions to add the various types of splits to the current layout
## for both row and column. These all act as wrappers to the split_cols and
## split_rows method stacks.
#' Declaring a column-split based on levels of a variable
#'
#' Will generate children for each subset of a categorical variable.
#'
#' @inheritParams lyt_args
#' @param ref_group (`string` or `NULL`)\cr level of `var` that should be considered `ref_group`/reference.
#'
#' @return A `PreDataTableLayouts` object suitable for passing to further layouting functions, and to [build_table()].
#'
#' @inheritSection custom_split_funs Custom Splitting Function Details
#'
#' @examples
#' lyt <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' analyze(c("AGE", "BMRKR2"))
#'
#' tbl <- build_table(lyt, ex_adsl)
#' tbl
#'
#' # Let's look at the splits in more detail
#'
#' lyt1 <- basic_table() %>% split_cols_by("ARM")
#' lyt1
#'
#' # add an analysis (summary)
#' lyt2 <- lyt1 %>%
#' analyze(c("AGE", "COUNTRY"),
#' afun = list_wrap_x(summary),
#' format = "xx.xx"
#' )
#' lyt2
#'
#' tbl2 <- build_table(lyt2, DM)
#' tbl2
#'
#' # By default sequentially adding layouts results in nesting
#' library(dplyr)
#'
#' DM_MF <- DM %>%
#' filter(SEX %in% c("M", "F")) %>%
#' mutate(SEX = droplevels(SEX))
#'
#' lyt3 <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_cols_by("SEX") %>%
#' analyze(c("AGE", "COUNTRY"),
#' afun = list_wrap_x(summary),
#' format = "xx.xx"
#' )
#' lyt3
#'
#' tbl3 <- build_table(lyt3, DM_MF)
#' tbl3
#'
#' # nested=TRUE vs not
#' lyt4 <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_rows_by("SEX", split_fun = drop_split_levels) %>%
#' split_rows_by("RACE", split_fun = drop_split_levels) %>%
#' analyze("AGE")
#' lyt4
#'
#' tbl4 <- build_table(lyt4, DM)
#' tbl4
#'
#' lyt5 <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_rows_by("SEX", split_fun = drop_split_levels) %>%
#' analyze("AGE") %>%
#' split_rows_by("RACE", nested = FALSE, split_fun = drop_split_levels) %>%
#' analyze("AGE")
#' lyt5
#'
#' tbl5 <- build_table(lyt5, DM)
#' tbl5
#'
#' @author Gabriel Becker
#' @export
split_cols_by <- function(lyt,
var,
labels_var = var,
split_label = var,
split_fun = NULL,
format = NULL,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
extra_args = list(),
ref_group = NULL) { ## ,
if (is.null(ref_group)) {
spl <- VarLevelSplit(
var = var,
split_label = split_label,
labels_var = labels_var,
split_format = format,
child_labels = child_labels,
split_fun = split_fun,
extra_args = extra_args
)
} else {
spl <- VarLevWBaselineSplit(
var = var,
ref_group = ref_group,
split_label = split_label,
split_fun = split_fun,
labels_var = labels_var,
split_format = format
)
}
pos <- next_cpos(lyt, nested)
split_cols(lyt, spl, pos)
}
## .tl_indent ====
setGeneric(".tl_indent_inner", function(lyt) standardGeneric(".tl_indent_inner"))
setMethod(
".tl_indent_inner", "PreDataTableLayouts",
function(lyt) .tl_indent_inner(rlayout(lyt))
)
setMethod(
".tl_indent_inner", "PreDataRowLayout",
function(lyt) {
if (length(lyt) == 0 || length(lyt[[1]]) == 0) {
0L
} else {
.tl_indent_inner(lyt[[length(lyt)]])
}
}
)
setMethod(
".tl_indent_inner", "SplitVector",
function(lyt) {
sum(vapply(lyt, function(x) label_position(x) == "topleft", TRUE)) - 1L
}
) ## length(lyt) - 1L)
.tl_indent <- function(lyt, nested = TRUE) {
if (!nested) {
0L
} else {
.tl_indent_inner(lyt)
}
}
#' Add rows according to levels of a variable
#'
#' @inheritParams lyt_args
#'
#' @inherit split_cols_by return
#'
#' @inheritSection custom_split_funs Custom Splitting Function Details
#'
#' @note
#' If `var` is a factor with empty unobserved levels and `labels_var` is specified, it must also be a factor
#' with the same number of levels as `var`. Currently the error that occurs when this is not the case is not very
#' informative, but that will change in the future.
#'
#' @examples
#' lyt <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_rows_by("RACE", split_fun = drop_split_levels) %>%
#' analyze("AGE", mean, var_labels = "Age", format = "xx.xx")
#'
#' tbl <- build_table(lyt, DM)
#' tbl
#'
#' lyt2 <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_rows_by("RACE") %>%
#' analyze("AGE", mean, var_labels = "Age", format = "xx.xx")
#'
#' tbl2 <- build_table(lyt2, DM)
#' tbl2
#'
#' lyt3 <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_cols_by("SEX") %>%
#' summarize_row_groups(label_fstr = "Overall (N)") %>%
#' split_rows_by("RACE",
#' split_label = "Ethnicity", labels_var = "ethn_lab",
#' split_fun = drop_split_levels
#' ) %>%
#' summarize_row_groups("RACE", label_fstr = "%s (n)") %>%
#' analyze("AGE", var_labels = "Age", afun = mean, format = "xx.xx")
#'
#' lyt3
#'
#' library(dplyr)
#'
#' DM2 <- DM %>%
#' filter(SEX %in% c("M", "F")) %>%
#' mutate(
#' SEX = droplevels(SEX),
#' gender_lab = c(
#' "F" = "Female", "M" = "Male",
#' "U" = "Unknown",
#' "UNDIFFERENTIATED" = "Undifferentiated"
#' )[SEX],
#' ethn_lab = c(
#' "ASIAN" = "Asian",
#' "BLACK OR AFRICAN AMERICAN" = "Black or African American",
#' "WHITE" = "White",
#' "AMERICAN INDIAN OR ALASKA NATIVE" = "American Indian or Alaska Native",
#' "MULTIPLE" = "Multiple",
#' "NATIVE HAWAIIAN OR OTHER PACIFIC ISLANDER" =
#' "Native Hawaiian or Other Pacific Islander",
#' "OTHER" = "Other", "UNKNOWN" = "Unknown"
#' )[RACE]
#' )
#'
#' tbl3 <- build_table(lyt3, DM2)
#' tbl3
#'
#' @author Gabriel Becker
#' @export
split_rows_by <- function(lyt,
var,
labels_var = var,
split_label = var,
split_fun = NULL,
format = NULL,
na_str = NA_character_,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
label_pos = "hidden",
indent_mod = 0L,
page_by = FALSE,
page_prefix = split_label,
section_div = NA_character_) {
label_pos <- match.arg(label_pos, label_pos_values)
child_labels <- match.arg(child_labels)
spl <- VarLevelSplit(
var = var,
split_label = split_label,
label_pos = label_pos,
labels_var = labels_var,
split_fun = split_fun,
split_format = format,
split_na_str = na_str,
child_labels = child_labels,
indent_mod = indent_mod,
page_prefix = if (page_by) page_prefix else NA_character_,
section_div = section_div
)
pos <- next_rpos(lyt, nested)
ret <- split_rows(lyt, spl, pos)
ret
}
#' Associate multiple variables with columns
#'
#' In some cases, the variable to be ultimately analyzed is most naturally defined on a column, not a row, basis.
#' When we need columns to reflect different variables entirely, rather than different levels of a single
#' variable, we use `split_cols_by_multivar`.
#'
#' @inheritParams lyt_args
#'
#' @inherit split_cols_by return
#'
#' @seealso [analyze_colvars()]
#'
#' @examples
#' library(dplyr)
#'
#' ANL <- DM %>% mutate(value = rnorm(n()), pctdiff = runif(n()))
#'
#' ## toy example where we take the mean of the first variable and the
#' ## count of >.5 for the second.
#' colfuns <- list(
#' function(x) in_rows(mean = mean(x), .formats = "xx.x"),
#' function(x) in_rows("# x > 5" = sum(x > .5), .formats = "xx")
#' )
#'
#' lyt <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_cols_by_multivar(c("value", "pctdiff")) %>%
#' split_rows_by("RACE",
#' split_label = "ethnicity",
#' split_fun = drop_split_levels
#' ) %>%
#' summarize_row_groups() %>%
#' analyze_colvars(afun = colfuns)
#' lyt
#'
#' tbl <- build_table(lyt, ANL)
#' tbl
#'
#' @author Gabriel Becker
#' @export
split_cols_by_multivar <- function(lyt,
vars,
split_fun = NULL,
varlabels = vars,
varnames = NULL,
nested = TRUE,
extra_args = list()) {
spl <- MultiVarSplit(
vars = vars, split_label = "",
varlabels = varlabels,
varnames = varnames,
split_fun = split_fun,
extra_args = extra_args
)
pos <- next_cpos(lyt, nested)
split_cols(lyt, spl, pos)
}
#' Associate multiple variables with rows
#'
#' When we need rows to reflect different variables rather than different
#' levels of a single variable, we use `split_rows_by_multivar`.
#'
#' @inheritParams lyt_args
#'
#' @inherit split_rows_by return
#'
#' @seealso [split_rows_by()] for typical row splitting, and [split_cols_by_multivar()] to perform the same type of
#' split on a column basis.
#'
#' @examples
#' lyt <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_rows_by_multivar(c("SEX", "STRATA1")) %>%
#' summarize_row_groups() %>%
#' analyze(c("AGE", "SEX"))
#'
#' tbl <- build_table(lyt, DM)
#' tbl
#'
#' @export
split_rows_by_multivar <- function(lyt,
vars,
split_fun = NULL,
split_label = "",
varlabels = vars,
format = NULL,
na_str = NA_character_,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
indent_mod = 0L,
section_div = NA_character_,
extra_args = list()) {
child_labels <- match.arg(child_labels)
spl <- MultiVarSplit(
vars = vars, split_label = split_label, varlabels,
split_format = format,
split_na_str = na_str,
child_labels = child_labels,
indent_mod = indent_mod,
split_fun = split_fun,
section_div = section_div,
extra_args = extra_args
)
pos <- next_rpos(lyt, nested)
split_rows(lyt, spl, pos)
}
#' Split on static or dynamic cuts of the data
#'
#' Create columns (or row splits) based on values (such as quartiles) of `var`.
#'
#' @inheritParams lyt_args
#'
#' @details For dynamic cuts, the cut is transformed into a static cut by [build_table()] *based on the full dataset*,
#' before proceeding. Thus even when nested within another split in column/row space, the resulting split will reflect
#' the overall values (e.g., quartiles) in the dataset, NOT the values for subset it is nested under.
#'
#' @inherit split_cols_by return
#'
#' @examples
#' library(dplyr)
#'
#' # split_cols_by_cuts
#' lyt <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_cols_by_cuts("AGE",
#' split_label = "Age",
#' cuts = c(0, 25, 35, 1000),
#' cutlabels = c("young", "medium", "old")
#' ) %>%
#' analyze(c("BMRKR2", "STRATA2")) %>%
#' append_topleft("counts")
#'
#' tbl <- build_table(lyt, ex_adsl)
#' tbl
#'
#' # split_rows_by_cuts
#' lyt2 <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_rows_by_cuts("AGE",
#' split_label = "Age",
#' cuts = c(0, 25, 35, 1000),
#' cutlabels = c("young", "medium", "old")
#' ) %>%
#' analyze(c("BMRKR2", "STRATA2")) %>%
#' append_topleft("counts")
#'
#'
#' tbl2 <- build_table(lyt2, ex_adsl)
#' tbl2
#'
#' # split_cols_by_quartiles
#'
#' lyt3 <- basic_table() %>%
#' split_cols_by("ARM") %>%
#' split_cols_by_quartiles("AGE", split_label = "Age") %>%
#' analyze(c("BMRKR2", "STRATA2")) %>%
#' append_topleft("counts")
#'
#' tbl3 <- build_table(lyt3, ex_adsl)
#' tbl3
#'
#' # split_rows_by_quartiles
#' lyt4 <- basic_table(show_colcounts = TRUE) %>%
#' split_cols_by("ARM") %>%
#' split_rows_by_quartiles("AGE", split_label = "Age") %>%
#' analyze("BMRKR2") %>%
#' append_topleft(c("Age Quartiles", " Counts BMRKR2"))
#'
#' tbl4 <- build_table(lyt4, ex_adsl)
#' tbl4
#'
#' # split_cols_by_cutfun
#' cutfun <- function(x) {
#' cutpoints <- c(
#' min(x),
#' mean(x),
#' max(x)
#' )
#'
#' names(cutpoints) <- c("", "Younger", "Older")
#' cutpoints
#' }
#'
#' lyt5 <- basic_table() %>%
#' split_cols_by_cutfun("AGE", cutfun = cutfun) %>%
#' analyze("SEX")
#'
#' tbl5 <- build_table(lyt5, ex_adsl)
#' tbl5
#'
#' # split_rows_by_cutfun
#' lyt6 <- basic_table() %>%
#' split_cols_by("SEX") %>%
#' split_rows_by_cutfun("AGE", cutfun = cutfun) %>%
#' analyze("BMRKR2")
#'
#' tbl6 <- build_table(lyt6, ex_adsl)
#' tbl6
#'
#' @author Gabriel Becker
#' @export
#' @rdname varcuts
split_cols_by_cuts <- function(lyt, var, cuts,
cutlabels = NULL,
split_label = var,
nested = TRUE,
cumulative = FALSE) {
spl <- make_static_cut_split(
var = var,
split_label = split_label,
cuts = cuts,
cutlabels = cutlabels,
cumulative = cumulative
)
## if(cumulative)
## spl = as(spl, "CumulativeCutSplit")
pos <- next_cpos(lyt, nested)
split_cols(lyt, spl, pos)
}
#' @export
#' @rdname varcuts
split_rows_by_cuts <- function(lyt, var, cuts,
cutlabels = NULL,
split_label = var,
format = NULL,
na_str = NA_character_,
nested = TRUE,
cumulative = FALSE,
label_pos = "hidden",
section_div = NA_character_) {
label_pos <- match.arg(label_pos, label_pos_values)
## VarStaticCutSplit(
spl <- make_static_cut_split(var, split_label,
cuts = cuts,
cutlabels = cutlabels,
split_format = format,
split_na_str = na_str,
label_pos = label_pos,
cumulative = cumulative,
section_div = section_div
)
## if(cumulative)
## spl = as(spl, "CumulativeCutSplit")
pos <- next_rpos(lyt, nested)
split_rows(lyt, spl, pos)
}
#' @export
#' @rdname varcuts
split_cols_by_cutfun <- function(lyt, var,
cutfun = qtile_cuts,
cutlabelfun = function(x) NULL,
split_label = var,
nested = TRUE,
extra_args = list(),
cumulative = FALSE) {
spl <- VarDynCutSplit(var, split_label,
cutfun = cutfun,
cutlabelfun = cutlabelfun,
extra_args = extra_args,
cumulative = cumulative,
label_pos = "hidden"
)
pos <- next_cpos(lyt, nested)
split_cols(lyt, spl, pos)
}
#' @export
#' @rdname varcuts
split_cols_by_quartiles <- function(lyt, var, split_label = var,
nested = TRUE,
extra_args = list(),
cumulative = FALSE) {
split_cols_by_cutfun(
lyt = lyt,
var = var,
split_label = split_label,
cutfun = qtile_cuts,
cutlabelfun = function(x) {
c(
"[min, Q1]",
"(Q1, Q2]",
"(Q2, Q3]",
"(Q3, max]"
)
},
nested = nested,
extra_args = extra_args,
cumulative = cumulative
)
## spl = VarDynCutSplit(var, split_label, cutfun = qtile_cuts,
## cutlabelfun = function(x) c("[min, Q1]",
## "(Q1, Q2]",
## "(Q2, Q3]",
## "(Q3, max]"),
## split_format = format,
## extra_args = extra_args,
## cumulative = cumulative,
## label_pos = "hidden")
## pos = next_cpos(lyt, nested)
## split_cols(lyt, spl, pos)
}
#' @export
#' @rdname varcuts
split_rows_by_quartiles <- function(lyt, var, split_label = var,
format = NULL,
na_str = NA_character_,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
extra_args = list(),
cumulative = FALSE,
indent_mod = 0L,
label_pos = "hidden",
section_div = NA_character_) {
split_rows_by_cutfun(
lyt = lyt,
var = var,
split_label = split_label,
format = format,
na_str = na_str,
cutfun = qtile_cuts,
cutlabelfun = function(x) {
c(
"[min, Q1]",
"(Q1, Q2]",
"(Q2, Q3]",
"(Q3, max]"
)
},
nested = nested,
child_labels = child_labels,
extra_args = extra_args,
cumulative = cumulative,
indent_mod = indent_mod,
label_pos = label_pos,
section_div = section_div
)
## label_pos <- match.arg(label_pos, label_pos_values)
## spl = VarDynCutSplit(var, split_label, cutfun = qtile_cuts,
## cutlabelfun = ,
## split_format = format,
## child_labels = child_labels,
## extra_args = extra_args,
## cumulative = cumulative,
## indent_mod = indent_mod,
## label_pos = label_pos)
## pos = next_rpos(lyt, nested)
## split_rows(lyt, spl, pos)
}
qtile_cuts <- function(x) {
ret <- quantile(x)
names(ret) <- c(
"",
"1st qrtile",
"2nd qrtile",
"3rd qrtile",
"4th qrtile"
)
ret
}
#' @export
#' @rdname varcuts
split_rows_by_cutfun <- function(lyt, var,
cutfun = qtile_cuts,
cutlabelfun = function(x) NULL,
split_label = var,
format = NULL,
na_str = NA_character_,
nested = TRUE,
child_labels = c("default", "visible", "hidden"),
extra_args = list(),
cumulative = FALSE,
indent_mod = 0L,
label_pos = "hidden",
section_div = NA_character_) {
label_pos <- match.arg(label_pos, label_pos_values)
child_labels <- match.arg(child_labels)
spl <- VarDynCutSplit(var, split_label,
cutfun = cutfun,
cutlabelfun = cutlabelfun,
split_format = format,
split_na_str = na_str,
child_labels = child_labels,
extra_args = extra_args,
cumulative = cumulative,
indent_mod = indent_mod,
label_pos = label_pos,
section_div = section_div
)
pos <- next_rpos(lyt, nested)
split_rows(lyt, spl, pos)
}
#' .spl_context within analysis and split functions
#'
#' `.spl_context` is an optional parameter for any of rtables' special functions, i.e. `afun` (analysis function
#' in [analyze()]), `cfun` (content or label function in [summarize_row_groups()]), or `split_fun` (e.g. for
#' [split_rows_by()]).
#'
#' @details
#' The `.spl_context` `data.frame` gives information about the subsets of data corresponding to the splits within
#' which the current `analyze` action is nested. Taken together, these correspond to the path that the resulting (set
#' of) rows the analysis function is creating, although the information is in a slightly different form. Each split
#' (which correspond to groups of rows in the resulting table), as well as the initial 'root' "split", is represented
#' via the following columns:
#'
#' \describe{
#' \item{split}{The name of the split (often the variable being split).}
#' \item{value}{The string representation of the value at that split (`split`).}
#' \item{full_parent_df}{A `data.frame` containing the full data (i.e. across all columns) corresponding to the path
#' defined by the combination of `split` and `value` of this row *and all rows above this row*.}
#' \item{all_cols_n}{The number of observations corresponding to the row grouping (union of all columns).}
#' \item{column for each column in the table structure (*row-split and analyze contexts only*)}{These list columns
#' (named the same as `names(col_exprs(tab))`) contain logical vectors corresponding to the subset of this row's
#' `full_parent_df` corresponding to the column.}
#' \item{cur_col_id}{Identifier of the current column. This may be an internal name, constructed by pasting the
#' column path together.}
#' \item{cur_col_subset}{List column containing logical vectors indicating the subset of this row's `full_parent_df`
#' for the column currently being created by the analysis function.}
#' \item{cur_col_expr}{List of current column expression. This may be used to filter `.alt_df_row`, or any external
#' data, by column. Filtering `.alt_df_row` by columns produces `.alt_df`.}
#' \item{cur_col_n}{Integer column containing the observation counts for that split.}
#' \item{cur_col_split}{Current column split names. This is recovered from the current column path.}
#' \item{cur_col_split_val}{Current column split values. This is recovered from the current column path.}
#' }
#'
#' @note
#' Within analysis functions that accept `.spl_context`, the `all_cols_n` and `cur_col_n` columns of the data frame
#' will contain the 'true' observation counts corresponding to the row-group and row-group x column subsets of the
#' data. These numbers will not, and currently cannot, reflect alternate column observation counts provided by the
#' `alt_counts_df`, `col_counts` or `col_total` arguments to [build_table()].
#'
#' @name spl_context
NULL
#' Additional parameters within analysis and content functions (`afun`/`cfun`)
#'
#' @description
#' It is possible to add specific parameters to `afun` and `cfun`, in [analyze()] and [summarize_row_groups()],
#' respectively. These parameters grant access to relevant information like the row split structure (see
#' [spl_context]) and the predefined baseline (`.ref_group`).
#'
#' @details
#' We list and describe all the parameters that can be added to a custom analysis function below:
#'
#' \describe{
#' \item{.N_col}{Column-wise N (column count) for the full column being tabulated within.}
#' \item{.N_total}{Overall N (all observation count, defined as sum of column counts) for the tabulation.}
#' \item{.N_row}{Row-wise N (row group count) for the group of observations being analyzed (i.e. with no
#' column-based subsetting).}
#' \item{.df_row}{`data.frame` for observations in the row group being analyzed (i.e. with no column-based
#' subsetting).}
#' \item{.var}{Variable being analyzed.}
#' \item{.ref_group}{`data.frame` or vector of subset corresponding to the `ref_group` column including subsetting
#' defined by row-splitting. Only required/meaningful if a `ref_group` column has been defined.}
#' \item{.ref_full}{`data.frame` or vector of subset corresponding to the `ref_group` column without subsetting
#' defined by row-splitting. Only required/meaningful if a `ref_group` column has been defined.}
#' \item{.in_ref_col}{Boolean indicating if calculation is done for cells within the reference column.}
#' \item{.spl_context}{`data.frame` where each row gives information about a previous 'ancestor' split state.
#' See [spl_context].}
#' \item{.alt_df_row}{`data.frame`, i.e. the `alt_count_df` after row splitting. It can be used with
#' `.all_col_exprs` and `.spl_context` information to retrieve current faceting, but for `alt_count_df`.
#' It can be an empty table if all the entries are filtered out.}
#' \item{.alt_df}{`data.frame`, `.alt_df_row` but filtered by columns expression. This data present the same
#' faceting of main data `df`. This also filters `NA`s out if related parameters are set to do so (e.g. `inclNAs`
#' in [analyze()]). Similarly to `.alt_df_row`, it can be an empty table if all the entries are filtered out.}
#' \item{.all_col_exprs}{List of expressions. Each of them represents a different column splitting.}
#' \item{.all_col_counts}{Vector of integers. Each of them represents the global count for each column. It differs