/
tt_dotabulation.R
2044 lines (1890 loc) · 59.7 KB
/
tt_dotabulation.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
match_extra_args <- function(f,
.N_col,
.N_total,
.all_col_exprs,
.all_col_counts,
.var,
.ref_group = NULL,
.alt_df_row = NULL,
.alt_df = NULL,
.ref_full = NULL,
.in_ref_col = NULL,
.spl_context = NULL,
.N_row,
.df_row,
extras) {
# This list is always present
possargs <- c(
list(
.N_col = .N_col,
.N_total = .N_total,
.N_row = .N_row,
.df_row = .df_row,
.all_col_exprs = .all_col_exprs,
.all_col_counts = .all_col_counts
),
extras
)
## specialized arguments that must be named in formals, cannot go
## anonymously into ...
if (!is.null(.var) && nzchar(.var)) {
possargs <- c(possargs, list(.var = .var))
}
if (!is.null(.ref_group)) {
possargs <- c(possargs, list(.ref_group = .ref_group))
}
if (!is.null(.alt_df_row)) {
possargs <- c(possargs, list(.alt_df_row = .alt_df_row))
}
if (!is.null(.alt_df)) {
possargs <- c(possargs, list(.alt_df = .alt_df))
}
if (!is.null(.ref_full)) {
possargs <- c(possargs, list(.ref_full = .ref_full))
}
if (!is.null(.in_ref_col)) {
possargs <- c(possargs, list(.in_ref_col = .in_ref_col))
}
# Special case: .spl_context
if (!is.null(.spl_context) && !(".spl_context" %in% names(possargs))) {
possargs <- c(possargs, list(.spl_context = .spl_context))
} else {
possargs$.spl_context <- NULL
}
# Extra args handling
formargs <- formals(f)
formnms <- names(formargs)
exnms <- names(extras)
if (is.null(formargs)) {
return(NULL)
} else if ("..." %in% names(formargs)) {
formnms <- c(formnms, exnms[nzchar(exnms)])
}
possargs[names(possargs) %in% formnms]
}
#' @noRd
#' @return A `RowsVerticalSection` object representing the `k x 1` section of the
#' table being generated, with `k` the number of rows the analysis function
#' generates.
gen_onerv <- function(csub, col, count, cextr, cpath,
dfpart, func, totcount, splextra,
all_col_exprs,
all_col_counts,
takesdf = .takes_df(func),
baselinedf,
alt_dfpart,
inclNAs,
col_parent_inds,
spl_context) {
if (NROW(spl_context) > 0) {
spl_context$cur_col_id <- paste(cpath[seq(2, length(cpath), 2)], collapse = ".")
spl_context$cur_col_subset <- col_parent_inds
spl_context$cur_col_expr <- list(csub)
spl_context$cur_col_n <- vapply(col_parent_inds, sum, 1L)
spl_context$cur_col_split <- list(cpath[seq(1, length(cpath), 2)])
spl_context$cur_col_split_val <- list(cpath[seq(2, length(cpath), 2)])
}
# Making .alt_df from alt_dfpart (i.e. .alt_df_row)
if (NROW(alt_dfpart) > 0) {
alt_dfpart_fil <- alt_dfpart[eval(csub, envir = alt_dfpart), , drop = FALSE]
if (!is.null(col) && col %in% names(alt_dfpart_fil) && !inclNAs) {
alt_dfpart_fil <- alt_dfpart_fil[!is.na(alt_dfpart_fil[[col]]), ,
drop = FALSE
]
}
} else {
alt_dfpart_fil <- alt_dfpart
}
## workaround for https://github.com/insightsengineering/rtables/issues/159
if (NROW(dfpart) > 0) {
inds <- eval(csub, envir = dfpart)
dat <- dfpart[inds, , drop = FALSE]
} else {
dat <- dfpart
}
if (!is.null(col) && !inclNAs) {
dat <- dat[!is.na(dat[[col]]), , drop = FALSE]
}
fullrefcoldat <- cextr$.ref_full
if (!is.null(fullrefcoldat)) {
cextr$.ref_full <- NULL
}
inrefcol <- cextr$.in_ref_col
if (!is.null(fullrefcoldat)) {
cextr$.in_ref_col <- NULL
}
exargs <- c(cextr, splextra)
## behavior for x/df and ref-data (full and group)
## match
if (!is.null(col) && !takesdf) {
dat <- dat[[col]]
fullrefcoldat <- fullrefcoldat[[col]]
baselinedf <- baselinedf[[col]]
}
args <- list(dat)
names(all_col_counts) <- names(all_col_exprs)
exargs <- match_extra_args(func,
.N_col = count,
.N_total = totcount,
.all_col_exprs = all_col_exprs,
.all_col_counts = all_col_counts,
.var = col,
.ref_group = baselinedf,
.alt_df_row = alt_dfpart,
.alt_df = alt_dfpart_fil,
.ref_full = fullrefcoldat,
.in_ref_col = inrefcol,
.N_row = NROW(dfpart),
.df_row = dfpart,
.spl_context = spl_context,
extras = c(
cextr,
splextra
)
)
args <- c(args, exargs)
val <- do.call(func, args)
if (!is(val, "RowsVerticalSection")) {
if (!is(val, "list")) {
val <- list(val)
}
ret <- in_rows(
.list = val,
.labels = unlist(value_labels(val)),
.names = names(val)
)
} else {
ret <- val
}
ret
}
strip_multivar_suffix <- function(x) {
gsub("\\._\\[\\[[0-9]\\]\\]_\\.$", "", x)
}
## Generate all values (one for each column) for one or more rows
## by calling func once per column (as defined by cinfo)
#' @noRd
#' @return A list of `m` `RowsVerticalSection` objects, one for each (leaf) column in the table.
gen_rowvalues <- function(dfpart,
datcol,
cinfo,
func,
splextra,
takesdf = NULL,
baselines,
alt_dfpart,
inclNAs,
spl_context = spl_context) {
colexprs <- col_exprs(cinfo)
colcounts <- col_counts(cinfo)
colextras <- col_extra_args(cinfo, NULL)
cpaths <- col_paths(cinfo)
## XXX I don't think this is used anywhere???
## splextra = c(splextra, list(.spl_context = spl_context))
totcount <- col_total(cinfo)
colleaves <- collect_leaves(cinfo@tree_layout)
gotflist <- is.list(func)
## one set of named args to be applied to all columns
if (!is.null(names(splextra))) {
splextra <- list(splextra)
} else {
length(splextra) <- ncol(cinfo)
}
if (!gotflist) {
func <- list(func)
} else if (length(splextra) == 1) {
splextra <- rep(splextra, length.out = length(func))
}
## if(length(func)) == 1 && names(spl)
## splextra = list(splextra)
## we are in analyze_colvars, so we have to match
## the exargs value by position for each column repeatedly
## across the higher level col splits.
if (!is.null(datcol) && is.na(datcol)) {
datcol <- character(length(colleaves))
exargs <- vector("list", length(colleaves))
for (i in seq_along(colleaves)) {
x <- colleaves[[i]]
pos <- tree_pos(x)
spls <- pos_splits(pos)
## values have the suffix but we are populating datacol
## so it has to match var numbers so strip the suffixes back off
splvals <- strip_multivar_suffix(rawvalues(pos))
n <- length(spls)
datcol[i] <- if (is(spls[[n]], "MultiVarSplit")) {
splvals[n]
} else {
NA_character_
}
argpos <- match(datcol[i], spl_payload(spls[[n]]))
## single bracket here because assigning NULL into a list removes
## the position entirely
exargs[i] <- if (argpos <= length(splextra)) {
splextra[argpos]
} else {
list(NULL)
}
}
## })
if (all(is.na(datcol))) {
datcol <- list(NULL)
} else if (any(is.na(datcol))) {
stop("mix of var and non-var columns with NA analysis rowvara")
}
} else {
exargs <- splextra
if (is.null(datcol)) {
datcol <- list(NULL)
}
datcol <- rep(datcol, length(colexprs))
## if(gotflist)
## length(exargs) <- length(func) ## func is a list
exargs <- rep(exargs, length.out = length(colexprs))
}
allfuncs <- rep(func, length.out = length(colexprs))
if (is.null(takesdf)) {
takesdf <- .takes_df(allfuncs)
}
rawvals <- mapply(gen_onerv,
csub = colexprs,
col = datcol,
count = colcounts,
cextr = colextras,
cpath = cpaths,
baselinedf = baselines,
alt_dfpart = list(alt_dfpart),
func = allfuncs,
takesdf = takesdf,
col_parent_inds = spl_context[, names(colexprs),
drop = FALSE
],
all_col_exprs = list(colexprs),
all_col_counts = list(colcounts),
splextra = exargs,
MoreArgs = list(
dfpart = dfpart,
totcount = totcount,
inclNAs = inclNAs,
spl_context = spl_context
),
SIMPLIFY = FALSE
)
names(rawvals) <- names(colexprs)
rawvals
}
.strip_lst_rvals <- function(lst) {
lapply(lst, rawvalues)
}
#' @noRd
#' @return A list of table rows, even when only one is generated.
.make_tablerows <- function(dfpart,
alt_dfpart,
func,
cinfo,
datcol = NULL,
lev = 1L,
rvlab = NA_character_,
format = NULL,
defrowlabs = NULL,
rowconstr = DataRow,
splextra = list(),
takesdf = NULL,
baselines = replicate(
length(col_exprs(cinfo)),
list(dfpart[0, ])
),
inclNAs,
spl_context = context_df_row(cinfo = cinfo)) {
if (is.null(datcol) && !is.na(rvlab)) {
stop("NULL datcol but non-na rowvar label")
}
if (!is.null(datcol) && !is.na(datcol)) {
if (!all(datcol %in% names(dfpart))) {
stop(
"specified analysis variable (", datcol,
") not present in data"
)
}
rowvar <- datcol
} else {
rowvar <- NA_character_
}
rawvals <- gen_rowvalues(dfpart,
alt_dfpart = alt_dfpart,
datcol = datcol,
cinfo = cinfo,
func = func,
splextra = splextra,
takesdf = takesdf,
baselines = baselines,
inclNAs = inclNAs,
spl_context = spl_context
)
## if(is.null(rvtypes))
## rvtypes = rep(NA_character_, length(rawvals))
lens <- vapply(rawvals, length, NA_integer_)
unqlens <- unique(lens)
## length 0 returns are ok to not match cause they are
## just empty space we can fill in as needed.
if (length(unqlens[unqlens > 0]) != 1L) { ## length(unqlens) != 1 &&
## (0 %in% unqlens && length(unqlens) != 2)) {
stop(
"Number of rows generated by analysis function do not match ",
"across all columns. ",
if (!is.na(datcol) && is.character(dfpart[[datcol]])) {
paste(
"\nPerhaps convert analysis variable", datcol,
"to a factor?"
)
}
)
}
maxind <- match(max(unqlens), lens)
## look if we got labels, if not apply the
## default row labels
## this is guaranteed to be a RowsVerticalSection object.
rv1col <- rawvals[[maxind]]
## nocov start
if (!is(rv1col, "RowsVerticalSection")) {
stop(
"gen_rowvalues appears to have generated something that was not ",
"a RowsVerticalSection object. Please contact the maintainer."
)
}
# nocov end
labels <- value_labels(rv1col)
ncrows <- max(unqlens)
if (ncrows == 0) {
return(list())
}
stopifnot(ncrows > 0)
if (is.null(labels)) {
if (length(rawvals[[maxind]]) == length(defrowlabs)) {
labels <- defrowlabs
} else {
labels <- rep("", ncrows)
}
}
rfootnotes <- rep(list(list(), length(rv1col)))
nms <- value_names(rv1col)
rfootnotes <- row_footnotes(rv1col)
imods <- indent_mod(rv1col) ## rv1col@indent_mods
unwrapped_vals <- lapply(rawvals, as, Class = "list", strict = TRUE)
formatvec <- NULL
if (!is.null(format)) {
if (is.function(format)) {
format <- list(format)
}
formatvec <- rep(format, length.out = ncrows)
}
trows <- lapply(1:ncrows, function(i) {
rowvals <- lapply(unwrapped_vals, function(colvals) {
colvals[[i]]
})
imod <- unique(vapply(rowvals, indent_mod, 0L))
if (length(imod) != 1) {
stop(
"Different cells in the same row appear to have been given ",
"different indent_mod values"
)
}
rowconstr(
vals = rowvals,
cinfo = cinfo,
lev = lev,
label = labels[i],
name = nms[i], ## labels[i], ## XXX this is probably wrong?!
var = rowvar,
format = formatvec[[i]],
indent_mod = imods[[i]] %||% 0L,
footnotes = rfootnotes[[i]] ## one bracket so list
)
})
trows
}
.make_caller <- function(parent_cfun, clabelstr = "") {
formalnms <- names(formals(parent_cfun))
## note the <- here
if (!is.na(dotspos <- match("...", formalnms))) {
toremove <- dotspos
} else {
toremove <- NULL
}
labelstrpos <- match("labelstr", names(formals(parent_cfun)))
if (is.na(labelstrpos)) {
stop(
"content function does not appear to accept the labelstr",
"arguent"
)
}
toremove <- c(toremove, labelstrpos)
formalnms <- formalnms[-1 * toremove]
caller <- eval(parser_helper(text = paste(
"function() { parent_cfun(",
paste(formalnms, "=",
formalnms,
collapse = ", "
),
", labelstr = clabelstr, ...)}"
)))
formals(caller) <- c(
formals(parent_cfun)[-labelstrpos],
alist("..." = )
) # nolint
caller
}
# Makes content table xxx renaming
.make_ctab <- function(df,
lvl, ## treepos,
name,
label,
cinfo,
parent_cfun = NULL,
format = NULL,
na_str = NA_character_,
indent_mod = 0L,
cvar = NULL,
inclNAs,
alt_df,
extra_args,
spl_context = context_df_row(cinfo = cinfo)) {
if (length(cvar) == 0 || is.na(cvar) || identical(nchar(cvar), 0L)) {
cvar <- NULL
}
if (!is.null(parent_cfun)) {
## cfunc <- .make_caller(parent_cfun, label)
cfunc <- lapply(parent_cfun, .make_caller, clabelstr = label)
contkids <- tryCatch(
.make_tablerows(df,
lev = lvl,
func = cfunc,
cinfo = cinfo,
rowconstr = ContentRow,
datcol = cvar,
takesdf = rep(.takes_df(cfunc),
length.out = ncol(cinfo)
),
inclNAs = FALSE,
alt_dfpart = alt_df,
splextra = extra_args,
spl_context = spl_context
),
error = function(e) e
)
if (is(contkids, "error")) {
stop("Error in content (summary) function: ", contkids$message,
"\n\toccured at path: ",
spl_context_to_disp_path(spl_context),
call. = FALSE
)
}
} else {
contkids <- list()
}
ctab <- ElementaryTable(
kids = contkids,
name = paste0(name, "@content"),
lev = lvl,
labelrow = LabelRow(),
cinfo = cinfo,
iscontent = TRUE,
format = format,
indent_mod = indent_mod,
na_str = na_str
)
ctab
}
.make_analyzed_tab <- function(df,
alt_df,
spl,
cinfo,
partlabel = "",
dolab = TRUE,
lvl,
baselines,
spl_context) {
stopifnot(is(spl, "VAnalyzeSplit"))
check_validsplit(spl, df)
defrlabel <- spl@default_rowlabel
if (nchar(defrlabel) == 0 && !missing(partlabel) && nchar(partlabel) > 0) {
defrlabel <- partlabel
}
kids <- tryCatch(
.make_tablerows(df,
func = analysis_fun(spl),
defrowlabs = defrlabel, # XXX
cinfo = cinfo,
datcol = spl_payload(spl),
lev = lvl + 1L,
format = obj_format(spl),
splextra = split_exargs(spl),
baselines = baselines,
alt_dfpart = alt_df,
inclNAs = avar_inclNAs(spl),
spl_context = spl_context
),
error = function(e) e
)
# Adding section_div for DataRows (analyze leaves)
kids <- .set_kids_section_div(kids, spl_section_div(spl), "DataRow")
if (is(kids, "error")) {
stop("Error applying analysis function (var - ",
spl_payload(spl) %||% "colvars", "): ", kids$message,
"\n\toccured at (row) path: ",
spl_context_to_disp_path(spl_context),
call. = FALSE
)
}
lab <- obj_label(spl)
ret <- TableTree(
kids = kids,
name = obj_name(spl),
label = lab,
lev = lvl,
cinfo = cinfo,
format = obj_format(spl),
na_str = obj_na_str(spl),
indent_mod = indent_mod(spl)
)
labelrow_visible(ret) <- dolab
ret
}
#' @param ... all arguments to `recurse_applysplit`, methods may only use some of them.
#' @return A `list` of children to place at this level.
#'
#' @noRd
setGeneric(".make_split_kids", function(spl, have_controws, make_lrow, ...) {
standardGeneric(".make_split_kids")
})
## single AnalyzeSplit
setMethod(
".make_split_kids", "VAnalyzeSplit",
function(spl,
have_controws, ## unused here
make_lrow, ## unused here
...,
df,
alt_df,
lvl,
name,
cinfo,
baselines,
spl_context,
nsibs = 0) {
spvis <- labelrow_visible(spl)
if (is.na(spvis)) {
spvis <- nsibs > 0
}
ret <- .make_analyzed_tab(
df = df,
alt_df,
spl = spl,
cinfo = cinfo,
lvl = lvl + 1L,
dolab = spvis,
partlabel = obj_label(spl),
baselines = baselines,
spl_context = spl_context
)
indent_mod(ret) <- indent_mod(spl)
kids <- list(ret)
names(kids) <- obj_name(ret)
kids
}
)
# Adding section_divisors to TableRow
.set_kids_section_div <- function(lst, trailing_section_div_char, allowed_class = "VTableTree") {
if (!is.na(trailing_section_div_char)) {
lst <- lapply(
lst,
function(k) {
if (is(k, allowed_class)) {
trailing_section_div(k) <- trailing_section_div_char
}
k
}
)
}
lst
}
## 1 or more AnalyzeSplits
setMethod(
".make_split_kids", "AnalyzeMultiVars",
function(spl,
have_controws,
make_lrow, ## used here
spl_context,
...) { ## all passed directly down to VAnalyzeSplit method
avspls <- spl_payload(spl)
nspl <- length(avspls)
kids <- unlist(lapply(avspls,
.make_split_kids,
nsibs = nspl - 1,
have_controws = have_controws,
make_lrow = make_lrow,
spl_context = spl_context,
...
))
kids <- .set_kids_section_div(kids, spl_section_div(spl), "VTableTree")
## XXX this seems like it should be identical not !identical
## TODO FIXME
if (!identical(make_lrow, FALSE) && !have_controws && length(kids) == 1) {
## we only analyzed one var so
## we don't need an extra wrapper table
## in the structure
stopifnot(identical(
obj_name(kids[[1]]),
spl_payload(spl)
))
return(kids[[1]])
}
## this will be the variables
## nms = sapply(spl_payload(spl), spl_payload)
nms <- vapply(kids, obj_name, "")
labs <- vapply(kids, obj_label, "")
if (length(unique(nms)) != length(nms) && length(unique(nms)) != length(nms)) {
warning("Non-unique sibling analysis table names. Using Labels ",
"instead. Use the table_names argument to analyze to avoid ",
"this when analyzing the same variable multiple times.",
"\n\toccured at (row) path: ",
spl_context_to_disp_path(spl_context),
call. = FALSE
)
kids <- mapply(function(k, nm) {
obj_name(k) <- nm
k
}, k = kids, nm = labs, SIMPLIFY = FALSE)
nms <- labs
}
nms[is.na(nms)] <- ""
names(kids) <- nms
kids
}
)
setMethod(
".make_split_kids", "Split",
function(spl,
have_controws,
make_lrow,
...,
splvec, ## passed to recursive_applysplit
df, ## used to apply split
alt_df, ## used to apply split for alternative df
lvl, ## used to calculate innerlev
cinfo, ## used for sanity check
baselines, ## used to calc new baselines
spl_context) {
## do the core splitting of data into children for this split
rawpart <- do_split(spl, df, spl_context = spl_context)
dataspl <- rawpart[["datasplit"]]
## these are SplitValue objects
splvals <- rawpart[["values"]]
partlabels <- rawpart[["labels"]]
if (is.factor(partlabels)) {
partlabels <- as.character(partlabels)
}
nms <- unlist(value_names(splvals))
if (is.factor(nms)) {
nms <- as.character(nms)
}
## Get new baseline values
##
## XXX this is a lot of data churn, if it proves too slow
## we can
## a) check if any of the analyses (i.e. the afuns) need the baseline in this
## splitvec and not do any of this if not, or
## b) refactor row splitting to behave like column splitting
##
## (b) seems the better design but is a major reworking of the guts of how
## rtables tabulation works
## (a) will only help if analyses that use baseline
## info are mixed with those who don't.
newbl_raw <- lapply(baselines, function(dat) {
# If no ref_group is specified
if (is.null(dat)) {
return(NULL)
}
## apply the same splitting on the
bldataspl <- tryCatch(do_split(spl, dat, spl_context = spl_context)[["datasplit"]],
error = function(e) e
)
# Error localization
if (is(bldataspl, "error")) {
stop("Following error encountered in splitting .ref_group (baselines): ",
bldataspl$message,
call. = FALSE
)
}
## we only keep the ones corresponding with actual data splits
res <- lapply(
names(dataspl),
function(nm) {
if (nm %in% names(bldataspl)) {
bldataspl[[nm]]
} else {
dataspl[[1]][0, ]
}
}
)
names(res) <- names(dataspl)
res
})
newbaselines <- lapply(names(dataspl), function(nm) {
lapply(newbl_raw, function(rawdat) {
if (nm %in% names(rawdat)) {
rawdat[[nm]]
} else {
rawdat[[1]][0, ]
}
})
})
if (length(newbaselines) != length(dataspl)) {
stop(
"Baselines (ref_group) after row split does not have",
" the same number of levels of input data split. ",
"Contact the maintainer."
) # nocov
}
if (!(length(newbaselines) == 0 ||
identical(
unique(sapply(newbaselines, length)),
length(col_exprs(cinfo))
))) {
stop(
"Baselines (ref_group) do not have the same number of columns",
" in each split. Contact the maintainer."
) # nocov
}
# If params are not present do not do the calculation
acdf_param <- check_afun_cfun_params(
SplitVector(spl, splvec),
c(".alt_df", ".alt_df_row")
)
# Apply same split for alt_counts_df
if (!is.null(alt_df) && any(acdf_param)) {
alt_dfpart <- tryCatch(
do_split(spl, alt_df,
spl_context = spl_context
)[["datasplit"]],
error = function(e) e
)
# Removing NA rows - to explore why this happens at all in a split
# This would be a fix but it is done in post-processing instead of pre-proc -> xxx
# x alt_dfpart <- lapply(alt_dfpart, function(data) {
# x data[!apply(is.na(data), 1, all), ]
# x })
# Error localization
if (is(alt_dfpart, "error")) {
stop("Following error encountered in splitting alt_counts_df: ",
alt_dfpart$message,
call. = FALSE
)
}
# Error if split does not have the same values in the alt_df (and order)
# The following breaks if there are different levels (do_split returns empty list)
# or if there are different number of the same levels. Added handling of NAs
# in the values of the factor when is all only NAs
is_all_na <- all(is.na(alt_df[[spl_payload(spl)]]))
if (!all(names(dataspl) %in% names(alt_dfpart)) || length(alt_dfpart) != length(dataspl) || is_all_na) {
alt_df_spl_vals <- unique(alt_df[[spl_payload(spl)]])
end_part <- ""
if (!all(alt_df_spl_vals %in% levels(alt_df_spl_vals))) {
end_part <- paste0(
" and following levels: ",
paste_vec(levels(alt_df_spl_vals))
)
}
if (is_all_na) {
end_part <- ". Found only NAs in alt_counts_df split"
}
stop(
"alt_counts_df split variable(s) [", spl_payload(spl),
"] (in split ", as.character(class(spl)),
") does not have the same factor levels of df.\ndf has c(", '"',
paste(names(dataspl), collapse = '", "'), '"', ") levels while alt_counts_df has ",
ifelse(length(alt_df_spl_vals) > 0, paste_vec(alt_df_spl_vals), ""),
" unique values", end_part
)
}
} else {
alt_dfpart <- setNames(rep(list(NULL), length(dataspl)), names(dataspl))
}
innerlev <- lvl + (have_controws || is.na(make_lrow) || make_lrow)
## do full recursive_applysplit on each part of the split defined by spl
inner <- unlist(mapply(
function(dfpart, alt_dfpart, nm, label, baselines, splval) {
rsplval <- context_df_row(
split = obj_name(spl),
value = value_names(splval),
full_parent_df = list(dfpart),
cinfo = cinfo
)
## if(length(rsplval) > 0)
## rsplval <- setNames(rsplval, obj_name(spl))
recursive_applysplit(
df = dfpart,
alt_df = alt_dfpart,
name = nm,
lvl = innerlev,
splvec = splvec,
cinfo = cinfo,
make_lrow = label_kids(spl),
parent_cfun = content_fun(spl),
cformat = content_format(spl),
cna_str = content_na_str(spl),
partlabel = label,
cindent_mod = content_indent_mod(spl),
cvar = content_var(spl),
baselines = baselines,
cextra_args = content_extra_args(spl),
## splval should still be retaining its name
spl_context = rbind(spl_context, rsplval)
)
},
dfpart = dataspl,
alt_dfpart = alt_dfpart,
label = partlabels,
nm = nms,
baselines = newbaselines,
splval = splvals,
SIMPLIFY = FALSE
))
# Setting the kids section separator if they inherits VTableTree
inner <- .set_kids_section_div(
inner,
trailing_section_div_char = spl_section_div(spl),
allowed_class = "VTableTree"
)
## This is where we need to build the structural tables
## even if they are invisible because their labels are not
## not shown.
innertab <- TableTree(
kids = inner,
name = obj_name(spl),
labelrow = LabelRow(
label = obj_label(spl),
vis = isTRUE(vis_label(spl))
),
cinfo = cinfo,
iscontent = FALSE,
indent_mod = indent_mod(spl),
page_title = ptitle_prefix(spl)
)
## kids = inner
kids <- list(innertab)
kids
}
)
context_df_row <- function(split = character(),
value = character(),
full_parent_df = list(),
cinfo = NULL) {
ret <- data.frame(
split = split,
value = value,
full_parent_df = I(full_parent_df),
# parent_cold_inds = I(parent_col_inds),
stringsAsFactors = FALSE
)
if (nrow(ret) > 0) {
ret$all_cols_n <- nrow(full_parent_df[[1]])
} else {
ret$all_cols_n <- integer() ## should this be numeric??? This never happens
}
if (!is.null(cinfo)) {
if (nrow(ret) > 0) {
colcols <- as.data.frame(lapply(col_exprs(cinfo), function(e) {
vals <- eval(e, envir = full_parent_df[[1]])
if (identical(vals, TRUE)) {
vals <- rep(vals, length.out = nrow(full_parent_df[[1]]))
}
I(list(vals))
}))
} else {
colcols <- as.data.frame(rep(list(logical()), ncol(cinfo)))
}
names(colcols) <- names(col_exprs(cinfo))
ret <- cbind(ret, colcols)
}
ret
}
recursive_applysplit <- function(df,
lvl = 0L,
alt_df,
splvec,
name,
# label,
make_lrow = NA,
partlabel = "",