/
PivotTable.R
4687 lines (4579 loc) · 312 KB
/
PivotTable.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
#' R6 class that represents a pivot table.
#'
#' @description
#' The `PivotTable` class is the primary class for
#' constructing and interacting with a pivot table.
#'
#' @docType class
#' @importFrom R6 R6Class
#' @importFrom data.table data.table is.data.table
#' @import htmlwidgets
#' @import htmltools
#' @export
#' @format \code{\link{R6Class}} object.
#' @examples
#' # The package vignettes include extensive examples of working with the
#' # PivotTable class.
#' library(pivottabler)
#' pt <- PivotTable$new()
#' pt$addData(bhmtrains)
#' pt$addColumnDataGroups("TrainCategory")
#' pt$addRowDataGroups("TOC")
#' pt$defineCalculation(calculationName="TotalTrains",
#' summariseExpression="n()")
#' pt$renderPivot()
PivotTable <- R6::R6Class("PivotTable",
public = list(
#' @description
#' Create a new `PivotTable` object.
#' @param processingLibrary The package to use when processing data.
#' Must be one of "auto" (which today is dplyr), "dplyr" or "data.table".
#' @param evaluationMode Either "batch" (default) or "sequential" (legacy).
#' @param argumentCheckMode The level of argument checking to perform.
#' Must be one of "auto", "none", "minimal", "basic", "balanced" (default)
#' or "full".
#' @param theme A theme to use to style the pivot table. Either:\cr
#' (1) The name of a built in theme, or\cr
#' (2) A list of simple style settings, or\cr
#' (3) A `PivotStyles` object containing a full set of styles.\cr
#' See the "Styling" vignette for many examples.
#' @param replaceExistingStyles Default `FALSE` to retain existing styles in
#' the styles collection and add specified styles as new custom styles.
#' Specify `TRUE` to update the definitions of existing styles.
#' @param tableStyle Styling to apply to the table. Either:\cr
#' (1) The name of a built in style, or\cr
#' (2) A list of CSS style declarations, e.g.\cr
#' `list("font-weight"="bold", "color"="#0000FF")`, or\cr
#' (3) A `PivotStyle` object.
#' @param headingStyle Styling to apply to the headings.
#' See the `tableStyle` argument for details.
#' @param cellStyle Styling to apply to the normal cells.
#' See the `tableStyle` argument for details.
#' @param totalStyle Styling to apply to the total cells.
#' See the `tableStyle` argument for details.
#' @param compatibility A list containing compatibility options to force
#' legacy behaviours. See the NEWS file for details.
#' @param traceEnabled Default `FALSE`. Specify `TRUE` to generate a trace
#' for debugging purposes.
#' @param traceFile If tracing is enabled, the location to generate the trace file.
#' @return A new `PivotTable` object.
initialize = function(processingLibrary="auto", evaluationMode="batch", argumentCheckMode="auto",
theme=NULL, replaceExistingStyles=FALSE,
tableStyle=NULL, headingStyle=NULL, cellStyle=NULL, totalStyle=NULL,
compatibility=NULL, traceEnabled=FALSE, traceFile=NULL) {
checkArgument(4, TRUE, "PivotTable", "initialize", processingLibrary, missing(processingLibrary), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character", allowedValues=c("auto", "dplyr", "data.table"))
checkArgument(4, TRUE, "PivotTable", "initialize", evaluationMode, missing(evaluationMode), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character", allowedValues=c("batch", "sequential"))
checkArgument(4, TRUE, "PivotTable", "initialize", argumentCheckMode, missing(argumentCheckMode), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character", allowedValues=c("auto", "none", "minimal", "basic", "balanced", "full"))
checkArgument(4, TRUE, "PivotTable", "initialize", theme, missing(theme), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyles"), allowedListElementClasses="character")
checkArgument(4, TRUE, "PivotTable", "initialize", replaceExistingStyles, missing(replaceExistingStyles), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(4, TRUE, "PivotTable", "initialize", tableStyle, missing(tableStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle"))
checkArgument(4, TRUE, "PivotTable", "initialize", headingStyle, missing(headingStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle"))
checkArgument(4, TRUE, "PivotTable", "initialize", cellStyle, missing(cellStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle"))
checkArgument(4, TRUE, "PivotTable", "initialize", totalStyle, missing(totalStyle), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "PivotStyle"))
checkArgument(4, TRUE, "PivotTable", "initialize", compatibility, missing(compatibility), allowMissing=TRUE, allowNull=TRUE, allowedClasses="list", allowedListElementClasses=c("character", "integer", "numeric", "logical"))
checkArgument(4, TRUE, "PivotTable", "initialize", traceEnabled, missing(traceEnabled), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(4, TRUE, "PivotTable", "initialize", traceFile, missing(traceFile), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
if(argumentCheckMode=="auto") {
if (length(strsplit(packageDescription("pivottabler")$Version, "\\.")[[1]]) > 3) {
message("Development version of pivottabler detected: Using argumentCheckMode=full.\nThis may reduce performance. To override, specify the argumentCheckMode explicitly.\nargumentCheckMode values: none, minimal, basic, balanced (the normal default), full.")
private$p_argumentCheckMode <- 4
}
else private$p_argumentCheckMode <- 3
}
else if(argumentCheckMode=="none") private$p_argumentCheckMode <- 0
else if(argumentCheckMode=="minimal") private$p_argumentCheckMode <- 1
else if(argumentCheckMode=="basic") private$p_argumentCheckMode <- 2
else if(argumentCheckMode=="balanced") private$p_argumentCheckMode <- 3
else if(argumentCheckMode=="full") private$p_argumentCheckMode <- 4
else stop("PivotTable$initialize(): Unknown argumentCheckMode encountered.", call. = FALSE)
private$p_traceEnabled <- traceEnabled
if(private$p_traceEnabled&(!is.null(traceFile))) {
private$p_traceFile <- file(traceFile, open="w")
}
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$new", "Creating new Pivot Table...")
private$p_compatibility <- compatibility
if(processingLibrary=="auto") {
if(requireNamespace(package="dplyr", quietly=TRUE)==TRUE) private$p_processingLibrary <- "dplyr"
else if(requireNamespace(package="data.table", quietly=TRUE)==TRUE) private$p_processingLibrary <- "data.table"
else stop("PivotTable$initialize(): No suitable processing library found. Please install either the dplyr package or the data.table package.", call. = FALSE)
}
else if(processingLibrary=="data.table") {
if(requireNamespace(package="data.table", quietly=TRUE)==FALSE) {
stop("PivotTable$initialize(): data.table package cannot be loaded. Please check the package is installed and working.", call. = FALSE)
}
private$p_processingLibrary <- "data.table"
}
else if(processingLibrary=="dplyr") {
if(requireNamespace(package="dplyr", quietly=TRUE)==FALSE) {
stop("PivotTable$initialize(): dplyr package cannot be loaded. Please check the package is installed and working.", call. = FALSE)
}
private$p_processingLibrary <- "dplyr"
}
else stop("PivotTable$initialize(): Unknown processingLibrary encountered.", call. = FALSE)
private$p_evaluationMode <- evaluationMode
private$p_defaults <- list()
private$p_lastInstanceId <- 0
# Create the basic parts of the pivot table
private$p_data <- PivotData$new(parentPivot=self)
private$p_rowGroup <- PivotDataGroup$new(parentPivot=self, parentGroup=NULL, rowOrColumn="row", isLevelTotal=TRUE)
private$p_columnGroup <- PivotDataGroup$new(parentPivot=self, parentGroup=NULL, rowOrColumn="column", isLevelTotal=TRUE)
private$p_rowGrpHeaders <- list()
private$p_calculationsPosition <- NULL
private$p_calculationGroups <- PivotCalculationGroups$new(parentPivot=self)
private$p_cells <- PivotCells$new(self)
private$p_htmlRenderer <- PivotHtmlRenderer$new(parentPivot=self)
private$p_latexRenderer <- PivotLatexRenderer$new(parentPivot=self)
private$p_openxlsxRenderer <- PivotOpenXlsxRenderer$new(parentPivot=self)
private$p_timings <- list()
# apply theming and styles
if(is.null(theme)) {
private$p_styles <- getTheme(parentPivot=self, themeName="default")
}
else {
if("PivotStyles" %in% class(theme)) { private$p_styles <- theme }
else if("list" %in% class(theme)) {
private$p_styles <- getSimpleColoredTheme(parentPivot=self, themeName="coloredTheme", theme=theme)
}
else if("character" %in% class(theme)) {
if(tolower(trimws(theme))=="none") { theme <- "blank" }
private$p_styles <- getTheme(parentPivot=self, themeName=theme)
}
}
if(!is.null(tableStyle)) {
if("PivotStyle" %in% class(tableStyle)) { tableStyle <- tableStyle$declarations }
if("list" %in% class(tableStyle)) {
if(private$p_styles$isExistingStyle(private$p_styles$tableStyle)&&(!replaceExistingStyles)) {
private$p_styles$getStyle(private$p_styles$tableStyle)$setPropertyValues(declarations=tableStyle)
tableStyle <- private$p_styles$tableStyle
}
else {
private$p_styles$addStyle(styleName="customTableStyle", declarations=tableStyle)
tableStyle <- "customTableStyle"
}
}
if("character" %in% class(tableStyle)) { private$p_styles$tableStyle <- tableStyle }
}
if(!is.null(headingStyle)) {
if("PivotStyle" %in% class(headingStyle)) { headingStyle <- headingStyle$declarations }
# root style
rootStyle <- headingStyle
if("list" %in% class(rootStyle)) {
if(private$p_styles$isExistingStyle(private$p_styles$rootStyle)&&(!replaceExistingStyles)) {
private$p_styles$getStyle(private$p_styles$rootStyle)$setPropertyValues(declarations=rootStyle)
rootStyle <- private$p_styles$rootStyle
}
else {
private$p_styles$addStyle(styleName="customRootStyle", declarations=rootStyle)
rootStyle <- "customRootStyle"
}
}
if("character" %in% class(rootStyle)) { private$p_styles$rootStyle <- rootStyle }
# row heading style
rowHeaderStyle <- headingStyle
if("list" %in% class(rowHeaderStyle)) {
if(private$p_styles$isExistingStyle(private$p_styles$rowHeaderStyle)&&(!replaceExistingStyles)) {
private$p_styles$getStyle(private$p_styles$rowHeaderStyle)$setPropertyValues(declarations=rowHeaderStyle)
rowHeaderStyle <- private$p_styles$rowHeaderStyle
}
else {
private$p_styles$addStyle(styleName="customRowHeadingStyle", declarations=rowHeaderStyle)
rowHeaderStyle <- "customRowHeadingStyle"
}
}
if("character" %in% class(rowHeaderStyle)) { private$p_styles$rowHeaderStyle <- rowHeaderStyle }
# column heading style
colHeaderStyle <- headingStyle
if("list" %in% class(colHeaderStyle)) {
if(private$p_styles$isExistingStyle(private$p_styles$colHeaderStyle)&&(!replaceExistingStyles)) {
private$p_styles$getStyle(private$p_styles$colHeaderStyle)$setPropertyValues(declarations=colHeaderStyle)
colHeaderStyle <- private$p_styles$colHeaderStyle
}
else {
private$p_styles$addStyle(styleName="customColHeadingStyle", declarations=colHeaderStyle)
colHeaderStyle <- "customColHeadingStyle"
}
}
if("character" %in% class(colHeaderStyle)) { private$p_styles$colHeaderStyle <- colHeaderStyle }
}
if(!is.null(cellStyle)) {
if("PivotStyle" %in% class(cellStyle)) { cellStyle <- cellStyle$declarations }
if("list" %in% class(cellStyle)) {
if(private$p_styles$isExistingStyle(private$p_styles$cellStyle)&&(!replaceExistingStyles)) {
private$p_styles$getStyle(private$p_styles$cellStyle)$setPropertyValues(declarations=cellStyle)
cellStyle <- private$p_styles$cellStyle
}
else {
private$p_styles$addStyle(styleName="customCellStyle", declarations=cellStyle)
cellStyle <- "customCellStyle"
}
}
if("character" %in% class(cellStyle)) { private$p_styles$cellStyle <- cellStyle }
}
if(!is.null(totalStyle)) {
if("PivotStyle" %in% class(totalStyle)) { totalStyle <- totalStyle$declarations }
if("list" %in% class(totalStyle)) {
if(private$p_styles$isExistingStyle(private$p_styles$totalStyle)&&(!replaceExistingStyles)) {
private$p_styles$getStyle(private$p_styles$totalStyle)$setPropertyValues(declarations=totalStyle)
totalStyle <- private$p_styles$totalStyle
}
else {
private$p_styles$addStyle(styleName="customTotalStyle", declarations=totalStyle)
totalStyle <- "customTotalStyle"
}
}
if("character" %in% class(totalStyle)) { private$p_styles$totalStyle <- totalStyle }
}
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$new", "Created new Pivot Table.")
return(invisible())
},
#' @description
#' Specify default values for some function arguments.
#' @param ... Default values to specify. See details.
#' @details
#' Defaults can be set for the following arguments of
#' `pt$addRowDataGroups()` and `pt$addColumnDataGroups()`:
#' `logical` values: `addTotal`, `expandExistingTotals`, `visualTotals`.
#' `character` values: `totalPosition`, `totalCaption`.
#' `list` or `logical` values: `outlineBefore`, `outlineAfter`, `outlineTotal`.\cr
#' Errors are generated for default values that could not be set.\cr
#' Warnings are generated for attempts to set defaults that aren't supported.\cr
#' See the "A1. Appendix" vignette for more details.
#' @return No return value.
setDefault = function(...) {
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$setDefault", "Setting defaults...")
# get the defaults
args <- list(...)
# process each of the defaults...
invaligArgs <- vector("character", 0)
for(argName in names(args)) {
validArg <- FALSE
# skip defaults with no name
if(is.null(argName)||(nchar(argName)==0)) {
stop("PivotTable$setDefault(): Default with no name encountered. Arguments must be specified in the form name=value.", call. = FALSE)
}
# get value
argValue <- args[[argName]]
# logical defaults
if(argName %in% c("addTotal", "expandExistingTotals", "visualTotals")) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", paste0("setDefault(", argName, ")"), argValue, FALSE, allowMissing=FALSE, allowNull=FALSE, allowedClasses="logical")
private$p_defaults[[argName]] <- isTRUE(argValue)
validArg <- TRUE
}
# character defaults
if(argName %in% c("totalPosition", "totalCaption")) {
allowedValues <- NULL
if(argName=="totalPosition") allowedValues <- c("before", "after")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", paste0("setDefault(", argName, ")"), argValue, FALSE, allowMissing=FALSE, allowNull=FALSE, allowedClasses="character", allowedValues=allowedValues)
private$p_defaults[[argName]] <- argValue
validArg <- TRUE
}
# outline settings
if(argName %in% c("outlineBefore", "outlineAfter", "outlineTotal")) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", paste0("setDefault(", argName, ")"), argValue, FALSE, allowMissing=FALSE, allowNull=FALSE, allowedClasses="list")
cleanOutline <- NULL
if(argName=="outlineBefore") cleanOutline <- cleanOutlineArg(self, argValue)
else if(argName=="outlineAfter") cleanOutline <- cleanOutlineArg(self, argValue, defaultCaption="")
else if(argName=="outlineTotal") cleanOutline <- cleanOutlineArg(self, argValue, defaultCaption="Total", defaultIsEmpty=FALSE)
if(!is.null(cleanOutline)) private$p_defaults[[argName]] <- cleanOutline
validArg <- TRUE
}
# was it a valid argument?
if(validArg==FALSE) {
invaligArgs[length(invaligArgs)+1] <- argName
}
}
# warn about any unknown arguments
if(length(invaligArgs)>0) {
warning(paste0("PivotTable$setDefault(): Unknown default(s) encountered: ", paste(invaligArgs,collapse=", ")), call. = FALSE)
}
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$setDefault", "Set defaults.")
},
#' @description
#' Get the default value of an argument.
#' @param argValue The name and value of the argument.
#' @param useDefault Specify `TRUE` to use the default.
#' @details
#' Both the argument name and argument value are taken from the `argValue`
#' argument. The name is obtained from `as.character(substitute(argValue))`.
#' This function is designed to easily slot into existing code, e.g.
#' `getDefault1(addTotal, missing(addTotal))`.
#' @return The current value of the argument or the default value.
getDefault1 = function(argValue=NULL, useDefault=NULL) {
argName <- as.character(substitute(argValue))
return(invisible(self$getDefault2(argName=argName, argValue=argValue, useDefault=useDefault)))
},
#' @description
#' Get the default value of an argument.
#' @param argName The name of the argument.
#' @param argValue The current value of the argument.
#' @param useDefault Specify `TRUE` to use the default.
#' @return The current value of the argument or the default value.
getDefault2 = function(argName=NULL, argValue=NULL, useDefault=NULL) {
if(!isTRUE(useDefault)) return(invisible(argValue))
defaultNames <- names(private$p_defaults)
if(argName %in% defaultNames) return(invisible(private$p_defaults[[argName]]))
else return(invisible(argValue))
},
#' @description
#' Get the default value of an argument.
#' @param argName The name of the argument.
#' @return The default value.
getDefault3 = function(argName) {
defaultNames <- names(private$p_defaults)
if(argName %in% defaultNames) return(invisible(private$p_defaults[[argName]]))
else return(invisible(NULL))
},
#' @description
#' Get the next unique object instance identifier.
#' @details
#' R6 classes cannot be easily compared to check if two variables are both
#' referring to the same object instance. Instance ids are a mechanism to
#' work around this problem. Each data group and cell is assigned an
#' instance id during object creation, which enables reliable reference
#' comparisons.
#' @return An integer instance id.
getNextInstanceId = function() { # used for reliable object instance comparisons (since R6 cannot easily compare object instances)
private$p_lastInstanceId <- private$p_lastInstanceId + 1
return(invisible(private$p_lastInstanceId))
},
#' @description
#' Add a data frame with the specified name to the pivot table.
#' @param dataFrame The data frame to add.
#' @param dataName The name to be used to refer to the data frame.
#' If no name is specified, the data frame variable name from the
#' calling code is used, retrieved via `deparse(substitute(dataFrame))`.
#' @details
#' The name is used to refer to the data frame when generating data groups
#' or defining calculations. The pivot table tracks the first data frame
#' added as the default data frame, so if only a single data frame is used,
#' it is typically not necessary to ever explicitly refer to the name.
#' Pivot tables are typically based on a single data frame, however it
#' is possible to build a pivot table that uses data from multiple data
#' frames.
#' @return The `PivotData` object managing the data frames for the pivot table.
addData = function(dataFrame=NULL, dataName=NULL) {
timeStart <- proc.time()
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addData", dataFrame, missing(dataFrame), allowMissing=FALSE, allowNull=FALSE, allowedClasses="data.frame")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addData", dataName, missing(dataName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
}
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$addData", "Adding data to Pivot Table...")
dn <- dataName
if(is.null(dn)) dn <- deparse(substitute(dataFrame))
private$p_data$addData(dataFrame, dataName=dn)
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$addData", "Added data to Pivot Table.")
private$addTiming(paste0("addData(", dn, ")"), timeStart)
return(invisible(private$p_data))
},
#' @description
#' Add a data frame containing totals data with the specified name and
#' variables to the pivot table.
#' @param dataFrame The data frame to add.
#' @param dataName The name of the data frame to associate these totals with.
#' @param variableNames A vector specifying how the aggregate data/totals in
#' the data frame are grouped.
#' @details
#' When generating pivot tables, the package typically calculates cell values.
#' However, the package can also use provided values (i.e. carry out no
#' calculations). This presents a challenge in that the sub-totals and totals
#' in a pivot table display values at a higher aggregation level than the
#' normal cells in the body of the pivot table. This method allows further
#' data frames to be specified that contain aggregated versions of the data.
#' See the "Calculations" vignette for details and an example.
#' @return No return value.
addTotalData = function(dataFrame=NULL, dataName=NULL, variableNames=NULL) {
timeStart <- proc.time()
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addTotalData", dataFrame, missing(dataFrame), allowMissing=FALSE, allowNull=FALSE, allowedClasses="data.frame")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addTotalData", dataName, missing(dataName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addTotalData", variableNames, missing(variableNames), allowMissing=FALSE, allowNull=TRUE, allowedClasses="character")
}
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$addTotalData", "Adding totals data to Pivot Table...")
private$p_data$addTotalData(dataFrame, dataName=dataName, variableNames=variableNames)
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$addTotalData", "Added totals data to Pivot Table.")
private$addTiming("addTotalData()", timeStart)
return(invisible())
},
#' @description
#' Retrieve the data groups at the specified level or levels in the column
#' groups hierarchy.
#' @param level An integer value or vector specifying one or more level numbers.
#' Level 1 represents the first visible level of data groups.
#' @param collapse A logical value specifying whether the return value should be
#' simplified. See details.
#' @details
#' If `level` is a vector: If `collapse` is `FALSE`, then a list of lists is
#' returned, if `collapse` is `TRUE`, then a single combined list is returned.
#' @return A list containing `PivotDataGroup` objects.
getColumnGroupsByLevel = function(level=NULL, collapse=FALSE) {
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getColumnGroupsByLevel", "Getting level column groups...")
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "getColumnGroupsByLevel", level, missing(level), allowMissing=FALSE, allowNull=FALSE, allowedClasses=c("integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "getColumnGroupsByLevel", collapse, missing(collapse), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
}
# multiple levels
if(length(level)>1) {
fx <- function(x) { return(self$getColumnGroupsByLevel(level=x)) }
if(isTRUE(collapse)) { return(invisible(unlist(lapply(level, fx)))) }
else { return(invisible(lapply(level, fx))) }
}
# single level
if(level<1) stop("PivotTable$getColumnGroupsByLevel(): level must be greater than or equal to one.", call. = FALSE)
levelCount <- self$columnGroupLevelCount
if(level>levelCount) stop(paste0("PivotTable$getColumnGroupsByLevel(): level must be less than or equal to ", levelCount, "."), call. = FALSE)
grps <- private$p_columnGroup$getLevelGroups(level=level)
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getColumnGroupsByLevel", "Got level column groups.", list(count = length(grps)))
return(invisible(grps))
},
#' @description
#' [Deprecated: Use topColumnGroups instead]
#' Retrieve the first level of column data groups.
#' @return A list containing `PivotDataGroup` objects.
getTopColumnGroups = function() {
.Deprecated(new="topColumnGroups")
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getTopColumnGroups", "Getting top level column groups...")
grps <- private$p_columnGroup$childGroups
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getTopColumnGroups", "Got top level column groups.", list(count = length(grps)))
return(invisible(grps))
},
#' @description
#' [Deprecated: Use leafColumnGroups instead]
#' Retrieve the bottom level of column data groups.
#' @return A list containing `PivotDataGroup` objects.
getLeafColumnGroups = function() {
.Deprecated(new="leafColumnGroups")
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getLeafColumnGroups", "Getting leaf level column groups...")
leafGroups = list()
grps <- private$p_columnGroup$getLeafGroups(leafGroups)
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getLeafColumnGroups", "Got leaf level column groups.", list(count = length(grps)))
return(invisible(grps))
},
#' @description
#' Retrieve the leaf-level data group associated with a specific column or
#' columns.
#' @param c An integer column number or an integer vector of column numbers.
#' @return A `PivotDataGroup` object or a list of `PivotDataGroup` objects.
getLeafColumnGroup = function(c=NULL) {
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "getLeafColumnGroup", c, missing(c), allowMissing=FALSE, allowNull=FALSE, allowedClasses=c("integer", "numeric"))
}
# multiple columns
if(length(c)>1) {
return(invisible(lapply(c, self$getLeafColumnGroup)))
}
# single column
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getLeafColumnGroup", "Getting leaf level column group...")
if((private$p_evaluated)&&(!is.null(private$p_cells))) {
# retrieve directly from the cells instance
grp <- private$p_cells$getColumnGroup(c=c)
}
else {
# fall back to the slower method (requires navigating through the hierarchy)
grps <- self$leafColumnGroups
if(length(grps)>c) grp <- grps[[c]]
}
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getLeafColumnGroup", "Got leaf level column group.")
return(invisible(grp))
},
#' @description
#' Add a new column data group at the top level of the column group
#' hierarchy. The new group is added as the last child unless an index
#' is specified.
#' @details See the "Irregular Layout" vignette for details and examples.
#' @param variableName A character value that specifies the name of the
#' variable in the data frame that the group relates to and will filter.
#' @param filterType Must be one of "ALL", "VALUES", or "NONE" to specify
#' the filter type:\cr
#' ALL means no filtering is applied.\cr
#' VALUEs is the typical value used to specify that `variableName` is
#' filtered to only `values`.\cr
#' NONE means no data will match this data group.
#' @param values A vector that specifies the filter values applied to
#' `variableName` to select the data to match this row/column in the pivot
#' table.
#' @param doNotExpand Default value `FALSE` - specify `TRUE` to
#' prevent the high-level methods such as `addDataGroups()` from adding
#' child groups.
#' @param isEmpty Default value `FALSE`, specify `TRUE` to mark that
#' this group contains no data (e.g. if
#' it is part of a header or outline row)
#' @param isOutline Default value `FALSE` - specify `TRUE` to mark
#' that this data group is an outline group.
#' @param styleAsOutline Default value `FALSE` - specify `TRUE` to style
#' this data group as an outline group. Only applicable when
#' `isOutline` is `TRUE`.
#' @param captionTemplate A character value that specifies the template
#' for the data group caption, default "{values}".
#' @param caption Effectively a hard-coded caption that overrides the
#' built-in logic for generating a caption.
#' @param isTotal Default `FALSE` - specify `TRUE` to mark that this
#' data group is a total.
#' @param isLevelSubTotal Default `FALSE` - specify `TRUE` to mark that
#' this data group is a sub-total within a level.
#' @param isLevelTotal Default `FALSE` - specify `TRUE` to mark that
#' this data group is level total.
#' @param calculationGroupName For calculation groups, this character value
#' specifies the calculation group that `calculationName` belongs to.
#' @param calculationName For calculation groups, this character value
#' specifies the name of the calculation.
#' @param baseStyleName The style name for the data group.
#' @param styleDeclarations A list of CSS style declarations to overlay
#' on top of the base style.
#' @param insertAtIndex An integer that specifies the index in the list
#' of child groups where the new group should be inserted.
#' @param insertBeforeGroup Specifies an existing group that the new group
#' should be inserted before.
#' @param insertAfterGroup Specifies an existing group that the new group
#' should be inserted after
#' @param mergeEmptySpace A character value that specifies how empty space
#' should be merged. This is typically only used with outline groups
#' (so applies to row groups only, not column groups). Must be one of
#' "doNotMerge", "dataGroupsOnly", "cellsOnly", "dataGroupsAndCellsAs1" or
#' "dataGroupsAndCellsAs2". See the "Regular Layout" vignette
#' for more information.
#' @param cellBaseStyleName The style name for cells related to this data
#' group.
#' @param cellStyleDeclarations A list of CSS style declarations to overlay
#' on top of the base style for cells related to this data group
#' @param sortAnchor Used to specify sort behaviour for outline groups, must
#' be one of "fixed", "next" or "previous".
#' @param resetCells Default `TRUE` to reset any cells that currently exist
#' in the pivot table and trigger a recalculation of the pivot table when
#' it is next rendered.
#' @return The new `PivotDataGroup` object.
addColumnGroup = function(variableName=NULL, filterType="ALL", values=NULL,
doNotExpand=FALSE, isEmpty=FALSE, isOutline=FALSE, styleAsOutline=FALSE,
captionTemplate="{value}", caption=NULL,
isTotal=FALSE, isLevelSubTotal=FALSE, isLevelTotal=FALSE,
calculationGroupName=NULL, calculationName=NULL,
baseStyleName=NULL, styleDeclarations=NULL,
insertAtIndex=NULL, insertBeforeGroup=NULL, insertAfterGroup=NULL,
mergeEmptySpace=NULL, cellBaseStyleName=NULL, cellStyleDeclarations=NULL,
sortAnchor=NULL, resetCells=TRUE) {
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", variableName, missing(variableName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", filterType, missing(filterType), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character", allowedValues=c("ALL", "VALUES", "NONE"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", values, missing(values), allowMissing=TRUE, allowNull=TRUE, mustBeAtomic=TRUE)
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", doNotExpand, missing(doNotExpand), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", isEmpty, missing(isEmpty), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", isOutline, missing(isOutline), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", styleAsOutline, missing(styleAsOutline), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", captionTemplate, missing(captionTemplate), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", caption, missing(caption), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", isTotal, missing(isTotal), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", isLevelSubTotal, missing(isLevelSubTotal), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", isLevelTotal, missing(isLevelTotal), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", calculationGroupName, missing(calculationGroupName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", calculationName, missing(calculationName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", baseStyleName, missing(baseStyleName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", styleDeclarations, missing(styleDeclarations), allowMissing=TRUE, allowNull=TRUE, allowedClasses="list", allowedListElementClasses=c("character", "integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", insertAtIndex, missing(insertAtIndex), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", insertBeforeGroup, missing(insertBeforeGroup), allowMissing=TRUE, allowNull=TRUE, allowedClasses="PivotDataGroup")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", insertAfterGroup, missing(insertAfterGroup), allowMissing=TRUE, allowNull=TRUE, allowedClasses="PivotDataGroup")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", mergeEmptySpace, missing(mergeEmptySpace), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character", allowedValues=c("doNotMerge", "dataGroupsOnly", "cellsOnly", "dataGroupsAndCellsAs1", "dataGroupsAndCellsAs2"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", cellBaseStyleName, missing(cellBaseStyleName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", cellStyleDeclarations, missing(cellStyleDeclarations), allowMissing=TRUE, allowNull=TRUE, allowedClasses="list", allowedListElementClasses=c("character", "integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", sortAnchor, missing(sortAnchor), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character", allowedValues=c("fixed", "next", "previous"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnGroup", resetCells, missing(resetCells), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
}
if(private$p_argumentCheckMode==TRUE) private$p_traceEnabled("PivotTable$addColumnGroup", "Adding column group...",
list(captionTemplate=captionTemplate, caption=caption,
doNotExpand=doNotExpand, isEmpty=isEmpty, isOutline=isOutline, styleAsOutline=styleAsOutline,
isTotal=isTotal, isLevelSubTotal=isLevelSubTotal, isLevelTotal=isLevelTotal,
variableName=variableName, values=values,
calculationGroupName=calculationGroupName, calculationName=calculationName,
baseStyleName=baseStyleName, styleDeclarations=styleDeclarations,
mergeEmptySpace=mergeEmptySpace, cellBaseStyleName=cellBaseStyleName,
cellStyleDeclarations=cellStyleDeclarations, sortAnchor=sortAnchor,
resetCells=resetCells))
# default to style as outline if not specified
if(isOutline && missing(styleAsOutline)) styleAsOutline <- TRUE
# add the group
grp <- private$p_columnGroup$addChildGroup(variableName=variableName, filterType=filterType, values=values,
doNotExpand=doNotExpand, isEmpty=isEmpty, isOutline=isOutline, styleAsOutline=styleAsOutline,
captionTemplate=captionTemplate, caption=caption,
isTotal=isTotal, isLevelSubTotal=isLevelSubTotal, isLevelTotal=isLevelTotal,
calculationGroupName=calculationGroupName, calculationName=calculationName,
baseStyleName=baseStyleName, styleDeclarations=styleDeclarations,
insertAtIndex=insertAtIndex, insertBeforeGroup=insertBeforeGroup, insertAfterGroup=insertAfterGroup,
mergeEmptySpace=mergeEmptySpace, cellBaseStyleName=cellBaseStyleName, cellStyleDeclarations=cellStyleDeclarations,
sortAnchor=sortAnchor, resetCells=resetCells)
if(private$p_argumentCheckMode==TRUE) private$p_traceEnabled("PivotTable$addColumnGroup", "Added column group.")
return(invisible(grp))
},
#' @description
#' Add multiple new data groups to the column group hierarchy
#' based on the distinct values in a data frame
#' column or using explicitly specified data values.
#' See the "Data Groups" vignette for example usage.
#' @details
#' There are broadly three different ways to call `addColumnDataGroups()`:\cr
#' (1) dataName=name, fromData=TRUE, onlyCombinationsThatExist=TRUE - which
#' considers the ancestors of each existing data group to generate only those
#' combinations of values that exist in the data frame.\cr
#' (2) dataName=name, fromData=TRUE, onlyCombinationsThatExist=FALSE - which
#' ignores the ancestors of each existing data group and simply adds every
#' distinct value of the specified variable under every existing data group,
#' which can result in combinations of values in the pivot table that don't
#' exist in the data frame (i.e. blank rows/columns in the pivot table).\cr
#' (3) fromData=FALSE, explicitListOfValues=list(...) - simply adds every
#' value from the specified list under every existing data group.
#' @param variableName The name of the related column in the data frame(s) of
#' the pivot table.
#' @param atLevel The level number that specifies where to add the new
#' groups. Level 1 = on the first visible level of the hierarchy.
#' `NULL` = create a new level at the bottom of the hierarchy for the new
#' groups.
#' @param fromData Default `TRUE` to generate the new data groups based on the
#' data values that exist in the `variableName` column in the named data frame.
#' If `FALSE`, then `explicitListOfValues` must be specified.
#' @param dataName The name of the data frame (as specified in
#' `pt$addData()`) to read the data group values from.
#' @param dataSortOrder Must be one of "asc", "desc", "custom" or "none".
#' @param customSortOrder A vector values sorted into the desired order.
#' @param caption The template of data group captions to generate,
#' default "{value}".
#' @param dataFormat A character, list or custom function to format the
#' data value.
#' @param dataFmtFuncArgs A list that specifies any additional arguments to
#' pass to a custom format function.
#' @param onlyCombinationsThatExist Default `TRUE` to generate only
#' combinations of data groups that exist in the data frame.
#' @param explicitListOfValues A list of explicit values to create data
#' groups from. A data group is created for each element of the list.
#' If a list element is vector of values (with length greater than 1),
#' then a data group is created for multiple values instead of just
#' a single value.
#' @param calculationGroupName The calculation group that the new data groups
#' are related to.
#' @param expandExistingTotals Default `FALSE`, which means totals are not
#' broken down in multi-level hierarchies.
#' @param addTotal Default `TRUE`, which means sub-total and total data groups
#' are automatically added.
#' @param visualTotals Default `FALSE`, which means visual totals are disabled.
#' See the "Data Groups" vignette for more details about visual totals.
#' @param totalPosition Either "before" or "after" to specify where total groups
#' are created, default "after".
#' @param totalCaption The caption to display on total groups, default "Total".
#' @param onlyAddGroupIf A filter expression that can be used to more finely
#' control whether data groups are created at different locations in the
#' hierarchy. There must be at least one row that matches this filter and the
#' filters from the ancestor groups in order that the child group is created.
#' E.g. `MaxDisplayLevel>5`.
#' @param preGroupData Default `TRUE`, which means that the pivot table
#' pre-calculates the distinct combinations of variable values to reduce the CPU
#' time and elapsed time required to generate data groups.
#' Cannot be used in conjunction with the
#' @param baseStyleName The name of the style applied to this data group (i.e.
#' this row/column heading). The style must exist in the `PivotStyles` object
#' associated with the PivotTable.
#' @param styleDeclarations CSS style declarations that can override the base
#' style, expressed as a list, e.g. `list("font-weight"=bold")`.
#' @return A list of new `PivotDataGroup` objects that have been added.
addColumnDataGroups = function(variableName=NULL, atLevel=NULL, fromData=TRUE, # atLevel=1 is the top level, (since 1 is the top level as visible to the user)
dataName=NULL, dataSortOrder="asc", customSortOrder=NULL, caption="{value}", dataFormat=NULL, dataFmtFuncArgs=NULL,
onlyCombinationsThatExist=TRUE, explicitListOfValues=NULL, calculationGroupName=NULL,
expandExistingTotals=FALSE, addTotal=TRUE, visualTotals=FALSE, totalPosition="after", totalCaption="Total",
onlyAddGroupIf=NULL, preGroupData=TRUE, baseStyleName=NULL, styleDeclarations=NULL) {
timeStart <- proc.time()
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", variableName, missing(variableName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", atLevel, missing(atLevel), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", fromData, missing(fromData), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", dataName, missing(dataName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", dataSortOrder, missing(dataSortOrder), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character", allowedValues=c("asc", "desc", "custom", "none"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", customSortOrder, missing(customSortOrder), allowMissing=TRUE, allowNull=TRUE, mustBeAtomic=TRUE)
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", caption, missing(caption), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", dataFormat, missing(dataFormat), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "list", "function"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", dataFmtFuncArgs, missing(dataFmtFuncArgs), allowMissing=TRUE, allowNull=TRUE, allowedClasses="list")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", onlyCombinationsThatExist, missing(onlyCombinationsThatExist), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", explicitListOfValues, missing(explicitListOfValues), allowMissing=TRUE, allowNull=TRUE, allowedClasses="list", listElementsMustBeAtomic=TRUE)
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", calculationGroupName, missing(calculationGroupName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", expandExistingTotals, missing(expandExistingTotals), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", addTotal, missing(addTotal), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", visualTotals, missing(visualTotals), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", totalPosition, missing(totalPosition), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character", allowedValues=c("before", "after"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", totalCaption, missing(totalCaption), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", onlyAddGroupIf, missing(onlyAddGroupIf), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", preGroupData, missing(preGroupData), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", baseStyleName, missing(baseStyleName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addColumnDataGroups", styleDeclarations, missing(styleDeclarations), allowMissing=TRUE, allowNull=TRUE, allowedClasses="list", allowedListElementClasses=c("character", "integer", "numeric"))
}
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$addColumnDataGroups", "Adding column groups...",
list(variableName=variableName, atLevel=atLevel, fromData=fromData,
dataName=dataName, dataSortOrder=dataSortOrder, customSortOrder=customSortOrder,
caption=caption, dataFormat=dataFormat, dataFmtFuncArgs=dataFmtFuncArgs,
onlyCombinationsThatExist=onlyCombinationsThatExist, explicitListOfValues=explicitListOfValues,
calculationGroupName=calculationGroupName, expandExistingTotals=expandExistingTotals,
addTotal=addTotal, visualTotals=visualTotals, totalPosition=totalPosition, totalCaption=totalCaption,
onlyAddGroupIf=onlyAddGroupIf, preGroupData=preGroupData, baseStyleName=baseStyleName, styleDeclarations=styleDeclarations))
if((!is.null(styleDeclarations))&&(length(styleDeclarations)!=length(names(styleDeclarations))))
stop("PivotTable$addColumnDataGroups(): One or more style declarations are missing a name.", call. = FALSE)
levelsBelow <- NULL
if((!is.null(atLevel))&&(atLevel>0)) levelsBelow <- atLevel - 1
grp <- private$p_columnGroup$addDataGroups(variableName=variableName, atLevel=levelsBelow, fromData=fromData,
dataName=dataName, dataSortOrder=dataSortOrder, customSortOrder=customSortOrder,
caption=caption, dataFormat=dataFormat, dataFmtFuncArgs=dataFmtFuncArgs,
onlyCombinationsThatExist=onlyCombinationsThatExist, explicitListOfValues=explicitListOfValues,
calculationGroupName=calculationGroupName,
expandExistingTotals=self$getDefault1(expandExistingTotals, missing(expandExistingTotals)),
addTotal=self$getDefault1(addTotal, missing(addTotal)),
visualTotals=self$getDefault1(visualTotals, missing(visualTotals)),
totalPosition=self$getDefault1(totalPosition, missing(totalPosition)),
totalCaption=self$getDefault1(totalCaption, missing(totalCaption)),
onlyAddGroupIf=onlyAddGroupIf, preGroupData=preGroupData, baseStyleName=baseStyleName, styleDeclarations=styleDeclarations)
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$addColumnDataGroups", "Added column groups.")
private$addTiming(paste0("addColumnDataGroups(", variableName, ")"), timeStart)
return(invisible(grp))
},
#' @description
#' Normalise the column data group hierarchy so that all branches have the
#' same number of levels - accomplished by adding empty child data groups
#' where needed.
#' @param resetCells Default `TRUE` to reset any cells that currently exist
#' in the pivot table and trigger a recalculation of the pivot table when
#' it is next rendered.
#' @return A list of new `PivotDataGroup` objects that have been added.
normaliseColumnGroups = function(resetCells=TRUE) {
timeStart <- proc.time()
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$normaliseColumnGroups", "Normalising column groups...")
groupsAdded <- private$p_columnGroup$normaliseDataGroup(resetCells)
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$normaliseColumnGroups", "Normalised column groups.", list(groupsAdded = groupsAdded))
private$addTiming("normaliseColumnGroups", timeStart)
return(invisible())
},
#' @description
#' Sort column data groups either by the data group data value, caption,
#' a custom order or based on calculation result values.
#' @param levelNumber The level number to sort the data groups, e.g.
#' level 1 (default) sorts the data groups at level 1 of the hierarchy
#' (which is the first visible level of data groups).
#' @param orderBy Must be either "value", "caption", "calculation",
#' "customByValue" or "customByCaption".\cr
#' "value" sorts by the raw (i.e. unformatted) group value.\cr
#' "caption" sorts by the formatted character group caption.\cr
#' "calculation" sorts using one of the calculations defined in the pivot table.\cr
#' "customValue" sorts by the raw (i.e. unformatted) group value according to
#' the specified custom sort order.\cr
#' "customCaption" sorts by the formatted character group caption according to
#' the specified custom sort order.
#' @param customOrder A vector values sorted into the desired order.
#' @param sortOrder Must be either "asc" or "desc".
#' @param calculationGroupName If sorting using a calculation, the name of the
#' calculation group containing the specified calculation.
#' @param calculationName If sorting using a calculation, the name of the
#' calculation.
#' @param fromIndex A boundary to limit the sort operation.
#' @param toIndex A boundary to limit the sort operation.
#' @param resetCells Default `TRUE` to reset any cells that currently exist
#' in the pivot table and trigger a recalculation of the pivot table when
#' it is next rendered.
#' @return No return value.
sortColumnDataGroups = function(levelNumber=1, orderBy="calculation", customOrder=NULL, sortOrder="desc",
calculationGroupName="default", calculationName=NULL,
fromIndex=NULL, toIndex=NULL, resetCells=TRUE) {
timeStart <- proc.time()
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "sortColumnDataGroups", levelNumber, missing(levelNumber), allowMissing=TRUE, allowNull=FALSE, allowedClasses=c("integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "sortColumnDataGroups", orderBy, missing(orderBy), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character", allowedValues=c("value","caption","calculation","customByValue","customByCaption"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "sortColumnDataGroups", customOrder, missing(customOrder), allowMissing=TRUE, allowNull=TRUE, mustBeAtomic=TRUE)
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "sortColumnDataGroups", sortOrder, missing(sortOrder), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character", allowedValues=c("asc","desc"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "sortColumnDataGroups", calculationGroupName, missing(calculationGroupName), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "sortColumnDataGroups", calculationName, missing(calculationName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "sortColumnDataGroups", fromIndex, missing(fromIndex), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "sortColumnDataGroups", toIndex, missing(toIndex), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "sortColumnDataGroups", resetCells, missing(resetCells), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
}
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$sortColumnDataGroups", "Sorting column data groups...",
list(levelNumber=levelNumber, orderBy=orderBy, customOrder=customOrder, sortOrder=sortOrder,
calculationGroupName=calculationGroupName, calculationName=calculationName,
fromIndex=fromIndex, toIndex=toIndex, resetCells=resetCells))
if(levelNumber<1) stop("PivotTable$sortColumnDataGroups(): levelNumber must be 1 or above.", call. = FALSE)
private$p_columnGroup$sortDataGroups(levelNumber=levelNumber-1, orderBy=orderBy, customOrder=customOrder, sortOrder=sortOrder,
calculationGroupName=calculationGroupName, calculationName=calculationName,
fromIndex=fromIndex, toIndex=toIndex, resetCells=resetCells)
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$sortColumnDataGroups", "Sorted column data groups.")
private$addTiming("sortColumnDataGroups", timeStart)
return(invisible())
},
#' @description
#' Retrieve the data groups at the specified level or levels in the row groups
#' hierarchy.
#' @param level An integer value or vector specifying one or more level numbers.
#' Level 1 represents the first visible level of data groups.
#' @param collapse A logical value specifying whether the return value should be
#' simplified. See details.
#' @details
#' If `level` is a vector: If `collapse` is `FALSE`, then a list of lists is
#' returned, if `collapse` is `TRUE`, then a single combined list is returned.
#' @return A list containing `PivotDataGroup` objects.
getRowGroupsByLevel = function(level=NULL, collapse=FALSE) {
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getRowGroupsByLevel", "Getting level row groups...")
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "getRowGroupsByLevel", level, missing(level), allowMissing=FALSE, allowNull=FALSE, allowedClasses=c("integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "getRowGroupsByLevel", collapse, missing(collapse), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
}
# multiple levels
if(length(level)>1) {
fx <- function(x) { return(self$getRowGroupsByLevel(level=x)) }
if(isTRUE(collapse)) { return(invisible(unlist(lapply(level, fx)))) }
else { return(invisible(lapply(level, fx))) }
}
# single level
if(level<1) stop("PivotTable$getRowGroupsByLevel(): level must be greater than or equal to one.", call. = FALSE)
levelCount <- self$rowGroupLevelCount
if(level>levelCount) stop(paste0("PivotTable$getRowGroupsByLevel(): level must be less than or equal to ", levelCount, "."), call. = FALSE)
grps <- private$p_rowGroup$getLevelGroups(level=level)
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getRowGroupsByLevel", "Got level row groups", list(count = length(grps)))
return(invisible(grps))
},
#' @description
#' [Deprecated: Use topRowGroups instead]
#' Retrieve the first level of row data groups.
#' @return A list containing `PivotDataGroup` objects.
getTopRowGroups = function() {
.Deprecated(new="topRowGroups")
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getTopRowGroups", "Getting top level row groups...")
grps <- private$p_rowGroup$childGroups
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getTopRowGroups", "Got top level row groups", list(count = length(grps)))
return(invisible(grps))
},
#' @description
#' [Deprecated: Use leafRowGroups instead]
#' Retrieve the bottom level of row data groups.
#' @return A list containing `PivotDataGroup` objects.
getLeafRowGroups = function() {
.Deprecated(new="leafRowGroups")
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getLeafRowGroups", "Getting leaf level row groups...")
leafGroups = list()
grps <- private$p_rowGroup$getLeafGroups(leafGroups)
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getTopRowGroups", "Got leaf level row groups", list(count = length(grps)))
return(invisible(grps))
},
#' @description
#' Retrieve the leaf-level data group associated with a specific row or rows.
#' @param r An integer row number or an integer vector of row numbers.
#' @return A `PivotDataGroup` object or a list of `PivotDataGroup` objects.
getLeafRowGroup = function(r=NULL) {
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "getLeafRowGroup", r, missing(r), allowMissing=FALSE, allowNull=FALSE, allowedClasses=c("integer", "numeric"))
}
# multiple rows
if(length(r)>1) {
return(invisible(lapply(r, self$getLeafRowGroup)))
}
# single row
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getLeafRowGroup", "Getting leaf level row group...")
if((private$p_evaluated)&&(!is.null(private$p_cells))) {
# retrieve directly from the cells instance
grp <- private$p_cells$getRowGroup(r=r)
}
else {
# fall back to the slower method (requires navigating through the hierarchy)
grps <- self$leafRowGroups
if(length(grps)>r) grp <- grps[[r]]
}
if(private$p_traceEnabled==TRUE) self$trace("PivotTable$getLeafRowGroup", "Got leaf level row group.")
return(invisible(grp))
},
#' @description
#' Add a new column data group at the top level of the row group
#' hierarchy. The new group is added as the last child unless an index
#' is specified.
#' @details See the "Irregular Layout" vignette for details and examples.
#' @param variableName A character value that specifies the name of the
#' variable in the data frame that the group relates to and will filter.
#' @param filterType Must be one of "ALL", "VALUES", or "NONE" to specify
#' the filter type:\cr
#' ALL means no filtering is applied.\cr
#' VALUEs is the typical value used to specify that `variableName` is
#' filtered to only `values`.\cr
#' NONE means no data will match this data group.
#' @param values A vector that specifies the filter values applied to
#' `variableName` to select the data to match this row/column in the pivot
#' table.
#' @param doNotExpand Default value `FALSE` - specify `TRUE` to
#' prevent the high-level methods such as `addDataGroups()` from adding
#' child groups.
#' @param isEmpty Default value `FALSE`, specify `TRUE` to mark that
#' this group contains no data (e.g. if
#' it is part of a header or outline row)
#' @param isOutline Default value `FALSE` - specify `TRUE` to mark
#' that this data group is an outline group.
#' @param styleAsOutline Default value `FALSE` - specify `TRUE` to style
#' this data group as an outline group. Only applicable when
#' `isOutline` is `TRUE`.
#' @param captionTemplate A character value that specifies the template
#' for the data group caption, default "{values}".
#' @param caption Effectively a hard-coded caption that overrides the
#' built-in logic for generating a caption.
#' @param isTotal Default `FALSE` - specify `TRUE` to mark that this
#' data group is a total.
#' @param isLevelSubTotal Default `FALSE` - specify `TRUE` to mark that
#' this data group is a sub-total within a level.
#' @param isLevelTotal Default `FALSE` - specify `TRUE` to mark that
#' this data group is level total.
#' @param calculationGroupName For calculation groups, this character value
#' specifies the calculation group that `calculationName` belongs to.
#' @param calculationName For calculation groups, this character value
#' specifies the name of the calculation.
#' @param baseStyleName The style name for the data group.
#' @param styleDeclarations A list of CSS style declarations to overlay
#' on top of the base style.
#' @param insertAtIndex An integer that specifies the index in the list
#' of child groups where the new group should be inserted.
#' @param insertBeforeGroup Specifies an existing group that the new group
#' should be inserted before.
#' @param insertAfterGroup Specifies an existing group that the new group
#' should be inserted after
#' @param mergeEmptySpace A character value that specifies how empty space
#' should be merged. This is typically only used with outline groups
#' (so applies to row groups only, not column groups). Must be one of
#' "doNotMerge", "dataGroupsOnly", "cellsOnly", "dataGroupsAndCellsAs1" or
#' "dataGroupsAndCellsAs2". See the "Regular Layout" vignette
#' for more information.
#' @param cellBaseStyleName The style name for cells related to this data
#' group.
#' @param cellStyleDeclarations A list of CSS style declarations to overlay
#' on top of the base style for cells related to this data group
#' @param sortAnchor Used to specify sort behaviour for outline groups, must
#' be one of "fixed", "next" or "previous".
#' @param outlineLinkedGroupId Used to link an outline group to the value
#' data group which has the child data groups.
#' @param resetCells Default `TRUE` to reset any cells that currently exist
#' in the pivot table and trigger a recalculation of the pivot table when
#' it is next rendered.
#' @return The new `PivotDataGroup` object.
addRowGroup = function(variableName=NULL, filterType="ALL", values=NULL,
doNotExpand=FALSE, isEmpty=FALSE, isOutline=FALSE, styleAsOutline=FALSE,
captionTemplate="{value}", caption=NULL,
isTotal=FALSE, isLevelSubTotal=FALSE, isLevelTotal=FALSE,
calculationGroupName=NULL, calculationName=NULL,
baseStyleName=NULL, styleDeclarations=NULL,
insertAtIndex=NULL, insertBeforeGroup=NULL, insertAfterGroup=NULL,
mergeEmptySpace=NULL, cellBaseStyleName=NULL, cellStyleDeclarations=NULL,
sortAnchor=NULL, resetCells=TRUE) {
if(private$p_argumentCheckMode > 0) {
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", variableName, missing(variableName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", filterType, missing(filterType), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character", allowedValues=c("ALL", "VALUES", "NONE"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", values, missing(values), allowMissing=TRUE, allowNull=TRUE, mustBeAtomic=TRUE)
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", doNotExpand, missing(doNotExpand), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", isEmpty, missing(isEmpty), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", isOutline, missing(isOutline), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", styleAsOutline, missing(styleAsOutline), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", captionTemplate, missing(captionTemplate), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", caption, missing(caption), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("character", "integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", isTotal, missing(isTotal), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", isLevelSubTotal, missing(isLevelSubTotal), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", isLevelTotal, missing(isLevelTotal), allowMissing=TRUE, allowNull=FALSE, allowedClasses="logical")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", calculationGroupName, missing(calculationGroupName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", calculationName, missing(calculationName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", baseStyleName, missing(baseStyleName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", styleDeclarations, missing(styleDeclarations), allowMissing=TRUE, allowNull=TRUE, allowedClasses="list", allowedListElementClasses=c("character", "integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", insertAtIndex, missing(insertAtIndex), allowMissing=TRUE, allowNull=TRUE, allowedClasses=c("integer", "numeric"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", insertBeforeGroup, missing(insertBeforeGroup), allowMissing=TRUE, allowNull=TRUE, allowedClasses="PivotDataGroup")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", insertAfterGroup, missing(insertAfterGroup), allowMissing=TRUE, allowNull=TRUE, allowedClasses="PivotDataGroup")
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", mergeEmptySpace, missing(mergeEmptySpace), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character", allowedValues=c("doNotMerge", "dataGroupsOnly", "cellsOnly", "dataGroupsAndCellsAs1", "dataGroupsAndCellsAs2"))
checkArgument(private$p_argumentCheckMode, TRUE, "PivotTable", "addRowGroup", cellBaseStyleName, missing(cellBaseStyleName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character")