-
Notifications
You must be signed in to change notification settings - Fork 23
/
ds.table.R
1778 lines (1294 loc) · 55.4 KB
/
ds.table.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
#' @title ds.table calling aggregate functions tableDS and tableDS2
#' and assign function tableDS.assign
#' @description creates 1-dimensional, 2-dimensional and 3-dimensional
#' tables using the {table} function in native R.
#' @details the {ds.table} function selects numeric, integer or factor
#' variables on the serverside which define a contingency table with up to
#' three dimensions. The native R {table} function basically operates on
#' factors and if variables are specified that are integers or numerics
#' they are first coerced to factors. If the 1-dimensional, 2-dimensional or
#' 3-dimensional table generated from a given study satisfies appropriate
#' disclosure-control criteria it can be returned directly to
#' the clientside where it is presented as a study-specific
#' table and is also included in a combined table across all studies.
#'
#' The data custodian responsible for data security in a
#' given study can specify the minimum non-zero cell count that
#' determines whether the disclosure-control criterion can be viewed
#' as having been met. If the count in any one cell in a table falls
#' below the specified threshold (and is also non-zero)
#' the whole table is blocked and cannot be returned
#' to the clientside. However, even if a table is potentially
#' disclosive it can still be written to the serverside while
#' an empty representation of the structure of the table is returned
#' to the clientside. The contents of the cells in the serverside table
#' object are reflected in a vector of counts which is one component of
#' that table object.
#'
#' The true counts in the studyside vector
#' are replaced by a sequential set of cell-IDs running from 1:n
#' (where n is the total number of cells in the table) in the empty
#' representation of the structure of the potentially disclosive table
#' that is returned to the clientside. These cell-IDs reflect
#' the order of the counts in the true counts vector on the serverside.
#' In consequence, if the number 13 appears in a cell of the empty
#' table returned to the clientside, it means that the true count
#' in that same cell is held as the 13th element of the true count
#' vector saved on the serverside. This means that a data analyst
#' can still make use of the counts from a call to the {ds.table}
#' function to drive their ongoing analysis even when one or
#' more non-zero cell counts fall below the specified threshold
#' for potential disclosure risk.
#'
#' Because the table object on the
#' serverside cannot be visualised or transferred to the clientside,
#' DataSHIELD ensures that although it can, in this way, be used
#' to advance analysis, it does not create a direct risk of disclosure.
#'
#' The <rvar> argument identifies the variable defining the rows
#' in each of the 2 dimensional tables produced in the output.
#'
#' The <cvar>
#' argument identifies the variable defining the columns in the 2 dimensional
#' tables produced in the output.
#'
#' In creating a 3-dimensional table the
#' <stvar> ('separate tables') argument identifies the variable that
#' indexes the set of two dimensional tables in the output {ds.table}.
#'
#' As a minor technicality, it should be noted that
#' if a 1-dimensional table is required, one only need specify a value
#' for the <rvar> argument and any one dimensional table in the output
#' is presented as a row vectors and so technically the <rvar> variable
#' defines the columns in that 1 x n vector. However, the ds.table
#' function deals with 1-dimensional tables differently to 2 and 3
#' dimensional tables and key components of the output
#' for one dimensional tables are actually two dimensional: with
#' rows defined by <rvar> and with one column for each of the studies.
#'
#' The output list generated by {ds.table} contains tables based on counts
#' named "table.name_counts" and other tables reporting corresponding
#' column proportions ("table.name_col.props") or row proportions
#' ("table.name_row.props"). In one dimensional tables in the output the
#' output tables include _counts and _proportions. The latter are not
#' called _col.props or _row.props because, for the reasons noted
#' above, they are technically column proportions but are based on the
#' distribution of the <rvar> variable.
#'
#' If the <report.chisq.tests> argument is set to TRUE, chisq tests
#' are applied to every 2 dimensional table in the output and reported
#' as "chisq.test_table.name". The <report.chisq.tests> argument
#' defaults to FALSE.
#'
#' If there is at least one expected cell
#' counts < 5 in an output table, the native R <chisq.test> function
#' returns a warning. Because in a DataSHIELD setting this often means that
#' every study and several tables may return the same warning
#' and because it is debatable whether this warning is really
#' statistically important, the <suppress.chisq.warnings> argument
#' can be set to TRUE to block the warnings. However, it is defaulted to FALSE.
#' @param rvar is a character string (in inverted commas) specifiying the
#' name of the variable defining the rows in all of the 2 dimensional
#' tables that form the output. Please see 'details' above for more
#' information about one-dimensional tables when a variable name is provided
#' by <rvar> but <cvar> and <stvar> are both NULL
#' @param cvar is a character string specifiying the
#' name of the variable defining the columns in all of the 2 dimensional
#' tables that form the output.
#' @param stvar is a character string specifiying the
#' name of the variable that indexes the separate two dimensional
#' tables in the output if the call specifies a 3 dimensional table.
#' @param report.chisq.tests if TRUE, chisquared tests
#' are applied to every 2 dimensional table in the output and reported
#' as "chisq.test_table.name". Default = FALSE.
#' @param exclude this argument is passed through to the {table} function in
#' native R which is called by {tableDS}. The help for {table} in native R
#' indicates that 'exclude' specifies any levels that should be deleted for
#' all factors in rvar, cvar or stvar. If the <exclude> argument
#' does not include NA and if the <useNA> argument is not specified,
#' it implies <useNA> = "ifany". If you read the help for {table} in native R
#' including the 'details' and the 'examples' (particularly 'd.patho') you
#' will see that the response of {table} to different combinations of the
#' <exclude> and <useNA> arguments can be non-intuitive. This is particularly
#' so if there is more than one type of missing (eg. missing by observation
#' as well as missing because of an NaN response to a mathematical
#' function - such as log(-3.0)). In DataSHIELD, if you are in one
#' of these complex settings (which should not be very common) and
#' you cannot interpret the output that has been approached
#' you might try: (1) making sure that the variable producing the strange results
#' is of class factor rather than integer or numeric - although integers and
#' numerics are coerced to factors by {ds.table} they can occasionally behave less
#' well when the NA setting is complex; (2) specify both an <exclude> argument
#' e.g. exclude =c("NaN","3") and a <useNA> argument e.g. useNA= "no";
#' (3) if you are excluding multiple levels e.g exclude = c("NA","3")
#' then you can reduce this to one e.g. exclude= c("NA") and then remove
#' the 3s by deleting rows of data, or converting the 3s to a different value.
#' @param useNA this argument is passed through to the {table} function in
#' native R which is called by {tableDS}. The help for {table} in native R
#' indicates that it specifies whether to include NA values in the table.
#' For further information, please see the help for the <exclude> argument (above)
#' and/or the help for the {table} function in native R.
#' @param suppress.chisq.warnings if set to TRUE, the default warnings are
#' suppressed that would otherwise be produced by the {table} function in
#' native R whenever an expected cell count in one or more cells is less than 5.
#' Default is FALSE. Further details can be found under 'details' and the
#' help provided for the <report.chisq.tests> argument (above).
#' @param table.assign is a Boolean argument set by default to FALSE. If it is
#' FALSE the {ds.table} function acts as a standard aggregate function -
#' it returns the table that is specified in its call to the clientside
#' where it can be visualised and worked with by the analyst. But if
#' <table.assign> is TRUE, the same table object is also written to
#' the serverside. As explained under 'details' (above), this may be
#' useful when some elements of a table need to be used to drive forward the
#' overall analysis (e.g. to help select individuals for an analysis
#' sub-sample), but the required table cannot be visualised or returned
#' to the clientside because it fails disclosure rules.
#' @param newobj this a character string providing a name for the output
#' table object to be written to the serverside if <table.assign> is TRUE.
#' If no explicit name for the table object is specified, but <table.assign>
#' is nevertheless TRUE, the name for the serverside table object defaults
#' to 'newObj'.
#' @param datasources a list of \code{\link{DSConnection-class}} objects obtained after login. If the <datasources>
#' the default set of connections will be used: see \link{datashield.connections_default}.
#' If the <datasources> is to be specified, it should be set without
#' inverted commas: e.g. datasources=connections.em or datasources=default.connections. If you wish to
#' apply the function solely to e.g. the second connection server in a set of three,
#' the argument can be specified as: e.g. datasources=connections.em[2].
#' If you wish to specify the first and third connection servers in a set you specify:
#' e.g. datasources=connections.em[c(1,3)].
#' @param force.nfilter if <force.nfilter> is non-NULL it must be specified as
#' a positive integer represented as a character string: e.g. "173". This
#' the has the effect of the standard value of 'nfilter.tab' (often 1, 3, 5 or 10
#' depending what value the data custodian has selected for this particular
#' data set), to this new value (here, 173). CRUCIALLY, the {ds.table} function
#' only allows the standard value to be INCREASED. So if the standard value has
#' been set as 5 (as one of the R options set in the serverside connection), "6" and
#' "4981" would be allowable values for the <force.nfilter> argument but "4" or
#' "1" would not. The purpose of this argument is for the user or developer
#' to force the table to fail the disclosure control tests so the he/she can
#' see what then happens and check that it is behaving as anticipated/hoped.
#' @return Having created the requested table based on serverside data
#' it is returned to the clientside for the analyst to visualise (unless
#' it is blocked because it fails the disclosure control criteria or
#' there is an error for some other reason).
#'
#' The clientside output from
#' {ds.table} includes error messages that identify when the creation of a
#' table from a particular study has failed and why. If table.assign=TRUE,
#' {ds.table} also writes the requested table as an object named by
#' the <newobj> argument or set to 'newObj' by default.
#'
#' Further information
#' about the visible material passed to the clientside, and the optional
#' table object written to the serverside can be seen under 'details' (above).
#' @author Paul Burton and Alex Westerberg for DataSHIELD Development Team, 01/05/2020
#' @export
ds.table<-function(rvar=NULL, cvar=NULL, stvar=NULL,
report.chisq.tests=FALSE,
exclude = NULL,
useNA = c("ifany"),
suppress.chisq.warnings=FALSE,
table.assign=FALSE,
newobj=NULL,
datasources=NULL,
force.nfilter=NULL)
{
# if no connection login details are provided look for 'connection' objects in the environment
if(is.null(datasources)){
datasources <- datashield.connections_find()
}
# check if a value has been provided for xvar
if(is.null(rvar)){
return("Error: rvar must have a value which is a character string naming the row variable for the table")
}
if(!is.null(cvar)&&!is.character(cvar)){
return("Error: if cvar is not null, it must have a value which is a character string naming the column variable for the table")
}
if(!is.null(stvar)&&!is.character(stvar)){
return("Error: if stvar is not null, it must have a value which is a character string naming the variable coding separate tables for the table")
}
if(useNA!="no"&&useNA!="ifany"&&useNA!="always"){
return("Error: useNA must take one of the three values: 'no', 'ifany', or 'always'. Default is 'ifany'")
}
if(!is.null(force.nfilter)&&!is.character(force.nfilter)){
return("Error: if force.nfilter is not null, it must have a value which is a character string specifying an integer for the forced value of the nfilter")
}
#All arguments should be directly transmittable
rvar.transmit<-rvar
if(is.null(cvar))
{
cvar.transmit<-NULL
}
else
{
cvar.transmit<-cvar
}
if(is.null(stvar))
{
stvar.transmit<-NULL
}
else
{
stvar.transmit<-stvar
}
if(is.null(exclude))
{
exclude.transmit<-NULL
}
else
{
exclude.transmit<-paste0(as.character(exclude),collapse=",")
}
useNA.transmit<-useNA
if(is.null(force.nfilter))
{
force.nfilter.transmit<-NULL
}
else
{
force.nfilter.transmit<-force.nfilter
}
#CALL THE asFactorDS1 SERVER SIDE FUNCTION (AN AGGREGATE FUNCTION)
# FOR rvar, cvar AND stvar
#TO DETERMINE ALL OF THE LEVELS REQUIRED
rvar.asfactor.calltext <- call("asFactorDS1", rvar)
rvar.all.levels <- DSI::datashield.aggregate(datasources, rvar.asfactor.calltext)
numstudies <- length(datasources)
rvar.all.levels.all.studies <- NULL
for(j in 1:numstudies){
rvar.all.levels.all.studies <- c(rvar.all.levels.all.studies,rvar.all.levels[[j]])
}
rvar.all.unique.levels <- as.character(unique(rvar.all.levels.all.studies))
rvar.all.unique.levels.transmit <- paste0(rvar.all.unique.levels, collapse=",")
########################################################
if(!is.null(cvar)){
cvar.asfactor.calltext <- call("asFactorDS1", cvar)
cvar.all.levels <- DSI::datashield.aggregate(datasources, cvar.asfactor.calltext)
numstudies <- length(datasources)
cvar.all.levels.all.studies <- NULL
for(j in 1:numstudies){
cvar.all.levels.all.studies <- c(cvar.all.levels.all.studies,cvar.all.levels[[j]])
}
cvar.all.unique.levels <- as.character(unique(cvar.all.levels.all.studies))
cvar.all.unique.levels.transmit <- paste0(cvar.all.unique.levels, collapse=",")
}else{
cvar.all.unique.levels.transmit<-NULL
}
########################################################
if(!is.null(stvar)){
stvar.asfactor.calltext <- call("asFactorDS1", stvar)
stvar.all.levels <- DSI::datashield.aggregate(datasources, stvar.asfactor.calltext)
numstudies <- length(datasources)
stvar.all.levels.all.studies <- NULL
for(j in 1:numstudies){
stvar.all.levels.all.studies <- c(stvar.all.levels.all.studies,stvar.all.levels[[j]])
}
stvar.all.unique.levels <- as.character(unique(stvar.all.levels.all.studies))
stvar.all.unique.levels.transmit <- paste0(stvar.all.unique.levels, collapse=",")
}else{
stvar.all.unique.levels.transmit<-NULL
}
#ASSIGN TABLE TO SERVERSIDE IF REQUIRED
if(table.assign)
{
if(is.null(newobj))
{
newobj<-"newTable"
}
# CALL THE MAIN SERVER SIDE ASSIGN FUNCTION
calltext.assign <- call("tableDS.assign", rvar.transmit=rvar.transmit, cvar.transmit=cvar.transmit,
stvar.transmit=stvar.transmit, rvar.all.unique.levels.transmit=rvar.all.unique.levels.transmit,
cvar.all.unique.levels.transmit=cvar.all.unique.levels.transmit,
stvar.all.unique.levels.transmit=stvar.all.unique.levels.transmit,
exclude.transmit=exclude.transmit, useNA.transmit=useNA.transmit
)
DSI::datashield.assign(datasources, newobj, calltext.assign)
}
# CALL THE MAIN SERVER SIDE AGGREGATE FUNCTION
calltext <- call("tableDS", rvar.transmit=rvar.transmit, cvar.transmit=cvar.transmit,
stvar.transmit=stvar.transmit,rvar.all.unique.levels.transmit=rvar.all.unique.levels.transmit,
cvar.all.unique.levels.transmit=cvar.all.unique.levels.transmit,
stvar.all.unique.levels.transmit=stvar.all.unique.levels.transmit,
exclude.transmit=exclude.transmit, useNA.transmit=useNA.transmit,
force.nfilter.transmit=force.nfilter.transmit)
table.out<-DSI::datashield.aggregate(datasources, calltext)
#END OF MAIN FUNCTION LEADING UP TO CALL
##############################################################################
###############################################################################
#Take serverside output and set up arrays with the correct dimensions
#so all values of a given dimension in any study are included in the
#tables produced for each individual study and for the combined values
#across studies
#How many studies have returned tables
numsources.orig<-length(table.out)
table.out.orig<-table.out
#Check whether return is a table or an error message
valid.output<-rep(1,numsources.orig)
error.messages<-table.out
sum.valid<-0
study.names.valid<-NULL
list.temp<-NULL
for(ns in 1:numsources.orig)
{
if(class(table.out[[ns]])=="character")
{
valid.output[ns]<-0
error.messages[[ns]]<-table.out[[ns]]
}
else
{
error.messages[[ns]]<-"No errors reported from this study"
}
}
num.valid.studies<-sum(valid.output)
if(num.valid.studies==0)
{
validity.message<-"All studies failed for reasons identified below"
cat("\n",validity.message,"\n\n")
for(ns in 1:numsources.orig)
{
cat("\nStudy",ns,": ",error.messages[[ns]],"\n")
}
return(list(validity.message=validity.message,error.messages=error.messages))
}
for(ns in 1:numsources.orig)
{
if(valid.output[ns])
{
sum.valid<-sum.valid+1
if(sum.valid==num.valid.studies)
{
list.temp<-paste0(list.temp,"table.out.orig[[",ns,"]])")
study.names.valid<-c(study.names.valid,as.character(ns))
}
else
{
list.temp<-paste0(list.temp,"table.out.orig[[",ns,"]],")
study.names.valid<-c(study.names.valid,as.character(ns))
}
}
}
table.out.valid <- FALSE
list.text<-paste0("table.out.valid<-list(",list.temp)
eval(parse(text=list.text))
table.out<-table.out.valid
numsources<-length(table.out)
if(num.valid.studies>0&&num.valid.studies<numsources.orig)
{
validity.message<-"At least one study failed for reasons identified by 'error.messages':"
for(ns in 1:numsources.orig)
{
message.add<-paste0("Study",ns,": ",error.messages[[ns]])
validity.message<-c(validity.message,message.add)
}
# cat("\n",validity.message,"\n")
# for(ns in 1:numsources.orig)
# {
# cat("\nStudy",ns,": ",error.messages[[ns]])
# }
# cat("\n\n")
#table.out<-table.out.valid
#numsources<-length(table.out)
}
if(num.valid.studies==numsources.orig)
{
validity.message<-"Data in all studies were valid"
cat("\n",validity.message,"\n")
for(ns in 1:numsources.orig)
{
cat("\nStudy",ns,": ",error.messages[[ns]])
}
cat("\n\n")
}
#check all tables from all sources have the same number of dimensions
table.dimensions<-rep(0,numsources)
for(ns in 1:numsources)
{
table.dimensions[ns]<-length(dim(table.out[[ns]]))
}
#table.dimensions
all.dims.same<-TRUE
if(numsources>1)
{
for(ns in 1:(numsources-1))
{
if(table.dimensions[ns]!=table.dimensions[ns+1])
{
all.dims.same<-FALSE
return.message<-"Warning: tables in different sources have different numbers of dimensions. Please analyse and combine yourself from study.specific tables above"
print(return.message)
return(return.message)
}
}
if(all.dims.same)
{
num.table.dims<-table.dimensions[1]
}
else
{
num.table.dims<-NA
}
}
if(numsources==1)
{
num.table.dims<-table.dimensions[1]
}
#num.table.dims
######################################################################
#Work first with three dimensional tables
if(num.table.dims==3)
{
#identify all possible values of each dimension
rvar.dimnames<-NULL
cvar.dimnames<-NULL
stvar.dimnames<-NULL
for(ns in 1:numsources)
{
rvar.dimnames<-c(rvar.dimnames,dimnames(table.out[[ns]])$rvar)
rvar.dimnames[is.na(rvar.dimnames)]<-"NA"
cvar.dimnames<-c(cvar.dimnames,dimnames(table.out[[ns]])$cvar)
cvar.dimnames[is.na(cvar.dimnames)]<-"NA"
stvar.dimnames<-c(stvar.dimnames,dimnames(table.out[[ns]])$stvar)
stvar.dimnames[is.na(stvar.dimnames)]<-"NA"
}
rvar.dimnames.unique<-unique(rvar.dimnames)
cvar.dimnames.unique<-unique(cvar.dimnames)
stvar.dimnames.unique<-unique(stvar.dimnames)
#print(rvar.dimnames)
#print(rvar.dimnames.unique)
#print(cvar.dimnames.unique)
#print(stvar.dimnames.unique)
numcells.all.sources<-length(rvar.dimnames.unique)*length(cvar.dimnames.unique)*length(stvar.dimnames.unique)
#numcells.all.sources
empty.table.all.sources.col.1<-rep(rvar.dimnames.unique,times=(length(cvar.dimnames.unique)*length(stvar.dimnames.unique)))
empty.table.all.sources.col.1
empty.table.all.sources.col.2<-rep(rep(cvar.dimnames.unique,each=length(rvar.dimnames.unique)),times=length(stvar.dimnames.unique))
empty.table.all.sources.col.2
empty.table.all.sources.col.3<-rep(rep(stvar.dimnames.unique,each=(length(rvar.dimnames.unique)*length(cvar.dimnames.unique))))
empty.table.all.sources.col.3
empty.table.all.sources.col.4<-rep(0,times=(length(rvar.dimnames.unique)*length(cvar.dimnames.unique)*length(stvar.dimnames.unique)))
empty.table.all.sources.col.4
empty.table.all.sources<-cbind(empty.table.all.sources.col.1,empty.table.all.sources.col.2,
empty.table.all.sources.col.3,empty.table.all.sources.col.4)
#dimnames(empty.table.all.sources)<-list(NULL,NULL)
empty.table.all.sources[is.na(empty.table.all.sources)]<-"NA"
#print(empty.table.all.sources) #1 table length 36 empty values
dim.vector.all.sources<-c(length(rvar.dimnames.unique),length(cvar.dimnames.unique),
length(stvar.dimnames.unique),numsources)
array.all.sources<-array(data=NA,dim=dim.vector.all.sources,
dimnames=list(rvar.dimnames.unique,cvar.dimnames.unique,stvar.dimnames.unique,NULL))
names(dimnames(array.all.sources))<-c(rvar,cvar,stvar,"study")
#print(array.all.sources) #length 108 all NAs so the study specific template for dimnames
#has been correctly expanded to
#include all studies
#KEY LOOP
for(ns in 1:numsources)
{
#start with study 1 then 2 etc etc
numcells<-length(table.out[[ns]])
#print(numcells)
study.specific.dim.vect<-dim(table.out[[ns]])
study.specific.dim.vect
count.in.cell<-rep(NA,numcells)
stvar.mark<-rep("",numcells)
cvar.mark<-rep("",numcells)
rvar.mark<-rep("",numcells)
cells.so.far<-0
for(ss in 1:study.specific.dim.vect[3])
{
for(cc in 1:study.specific.dim.vect[2])
{
for(rr in 1:study.specific.dim.vect[1])
{
cells.so.far<-cells.so.far+1
count.in.cell[cells.so.far]<-table.out[[ns]][cells.so.far]
rvar.mark[cells.so.far]<-rvar.dimnames[rr]
cvar.mark[cells.so.far]<-cvar.dimnames[cc]
stvar.mark[cells.so.far]<-stvar.dimnames[ss]
}
}
}
table.current.study<-cbind(rvar.mark,cvar.mark,stvar.mark,count.in.cell)
table.current.study[is.na(table.current.study)]<-"NA"
#cat("current study =",ns)
#print(table.current.study)
array.current.study<-array(data=table.current.study[,4],dim=dim.vector.all.sources[1:3],
dimnames=list(rvar.dimnames.unique,cvar.dimnames.unique,stvar.dimnames.unique))
names(dimnames(array.current.study))<-c(rvar,cvar,stvar)
#array.current.study
#IS TABLE FOR CURRENT STUDY IDENTICAL IN STRUCTURE TO EMPTY TABLE OVERALL?
etas<-as.vector(empty.table.all.sources[,1:3])
tss<-as.vector(table.current.study[,1:3])
tables.identical<-FALSE
if((sum(etas==tss))==length(etas))tables.identical<-TRUE
#if the table structure is identical to the structure of the empty table from all sources
#then simply write the counts from the study specific table to the empty table from all sources
#and then that becomes the study.specific.table for the given study
#if structure not identical match rows in study specific table to rows in array.all.sources using
#the dimnames.x.num to index the equivalent rows then the dimnames.x to check
if(tables.identical)
{
#array.all.sources[,,,ns]<-array.current.study
}
#if(!tables.identical)
{
#set up sequential numeric code for each of the sorted unique values in each dimnames
dimnames.1<-dimnames(array.all.sources)[[1]]
dimnames.1.num<-1:length(dimnames.1)
#cbind(dimnames.1,dimnames.1.num)
dimnames.2<-dimnames(array.all.sources)[[2]]
dimnames.2.num<-1:length(dimnames.2)
#cbind(dimnames.2,dimnames.2.num)
dimnames.3<-dimnames(array.all.sources)[[3]]
dimnames.3.num<-1:length(dimnames.3)
#cbind(dimnames.3,dimnames.3.num)
#Map row in table from current study with equivalent row in array containing unique
#values from every study and check that the identified row in the full array contains
#the same dimnames values as the row in the current study table. If it does not,
#then rather than trying to second guess all possible ways this could go wrong
#simply stop processing and ask user to work with study specific tables to
#create table statistics he/she requires
index.current.study<-rep(NA,length(table.current.study[,1]))
index.overall<-rep(NA,(dim.vector.all.sources[1]*dim.vector.all.sources[2]*dim.vector.all.sources[3]))
for(oo in 1:length(table.current.study[,1]))
{
d1<-table.current.study[oo,1]
n1<-dimnames.1.num[dimnames.1==d1]
d2<-table.current.study[oo,2]
n2<-dimnames.2.num[dimnames.2==d2]
d3<-table.current.study[oo,3]
n3<-dimnames.3.num[dimnames.3==d3]
index.current.study<-oo
#index.overall applies to empty.table.all.sources.col.1 etc which are all of length dim1*dim2*dim3 because
#this was created before array.all.sources was replicated to include space for all studies. So calculations
#of index.overall do not need to take account of ns value
index.overall<-n1+dim.vector.all.sources[1]*(n2-1)+
dim.vector.all.sources[1]*dim.vector.all.sources[2]*(n3-1)
count.current.study.current.row<-table.current.study[oo,4]
#check dimnames all match
d1.a<-empty.table.all.sources.col.1[index.overall]
d2.a<-empty.table.all.sources.col.2[index.overall]
d3.a<-empty.table.all.sources.col.3[index.overall]
if(d1.a!=d1||d2.a!=d2||d3.a!=d3)
{
return.message= "Dimensions of tables not behaving sensibly across studies.Please check the data in each study and calculate counts and percentages, yourself, using the counts from the individual studies"
cat(return.message)
return(return.message)
}
#dimension markers match so allocate count to correct cell
#index.overall.extended.over.all.studies applies to array.all.sources which is of length dim1*dim2*dim3*numsources
#must therefore add dim.vector.all.sources[1]*dim.vector.all.sources[2]*dim.vector.all.sources[3]*(ns-1)
#to identify correct row in extended array which has the full dimnames structure replicated for each study
index.overall.extended.over.all.studies<-index.overall+
dim.vector.all.sources[1]*dim.vector.all.sources[2]*dim.vector.all.sources[3]*(ns-1)
array.all.sources[index.overall.extended.over.all.studies]<-count.current.study.current.row
}
dimnames(array.all.sources)[4]<-list(as.character(1:numsources))
#print(array.all.sources)
}#end of tables not identical loop
}#end of ns loop
#Combine across studies if requested
####################################
combine.array.all.sources<-as.numeric(array.all.sources[,,,1])
if(numsources>1)
{
for(ns in 2:numsources)
{
combine.array.all.sources<-combine.array.all.sources+as.numeric(array.all.sources[,,,ns])
}
}
combine.array.all.sources<-array(data=combine.array.all.sources,dim=dim(array.all.sources)[1:num.table.dims],
dimnames=dimnames(array.all.sources)[1:num.table.dims])
#print(combine.array.all.sources)
######################
#return(array.all.sources)
}#end of 3 dims loop
######################################################################
#Next work with two dimensional tables
if(num.table.dims==2)
{
#identify all possible values of each dimension
rvar.dimnames<-NULL
cvar.dimnames<-NULL
for(ns in 1:numsources)
{
rvar.dimnames<-c(rvar.dimnames,dimnames(table.out[[ns]])$rvar)
rvar.dimnames[is.na(rvar.dimnames)]<-"NA"
cvar.dimnames<-c(cvar.dimnames,dimnames(table.out[[ns]])$cvar)
cvar.dimnames[is.na(cvar.dimnames)]<-"NA"
}
rvar.dimnames.unique<-unique(rvar.dimnames)
cvar.dimnames.unique<-unique(cvar.dimnames)
numcells.all.sources<-length(rvar.dimnames.unique)*length(cvar.dimnames.unique)
empty.table.all.sources.col.1<-rep(rvar.dimnames.unique,times=(length(cvar.dimnames.unique)))
empty.table.all.sources.col.1
empty.table.all.sources.col.2<-rep(cvar.dimnames.unique,each=length(rvar.dimnames.unique))
empty.table.all.sources.col.2
empty.table.all.sources.col.3<-rep(0,times=(length(rvar.dimnames.unique)*length(cvar.dimnames.unique)))
empty.table.all.sources.col.3
empty.table.all.sources<-cbind(empty.table.all.sources.col.1,empty.table.all.sources.col.2,
empty.table.all.sources.col.3)
empty.table.all.sources[is.na(empty.table.all.sources)]<-"NA"
#print(empty.table.all.sources) #1 table length 36 empty values
dim.vector.all.sources<-c(length(rvar.dimnames.unique),length(cvar.dimnames.unique),numsources)
array.all.sources<-array(data=NA,dim=dim.vector.all.sources,
dimnames=list(rvar.dimnames.unique,cvar.dimnames.unique,NULL))
names(dimnames(array.all.sources))<-c(rvar,cvar,"study")
#print(array.all.sources) #length 108 all NAs so the study specific template for dimnames
#has been correctly expanded to
#include all studies
#KEY LOOP
for(ns in 1:numsources)
{
#start with study 1 then 2 etc etc
numcells<-length(table.out[[ns]])
#print(numcells)
study.specific.dim.vect<-dim(table.out[[ns]])
study.specific.dim.vect
count.in.cell<-rep(NA,numcells)
cvar.mark<-rep("",numcells)
rvar.mark<-rep("",numcells)
cells.so.far<-0
for(cc in 1:study.specific.dim.vect[2])
{
for(rr in 1:study.specific.dim.vect[1])
{
cells.so.far<-cells.so.far+1
count.in.cell[cells.so.far]<-table.out[[ns]][cells.so.far]
rvar.mark[cells.so.far]<-rvar.dimnames[rr]
cvar.mark[cells.so.far]<-cvar.dimnames[cc]
}
}
table.current.study<-cbind(rvar.mark,cvar.mark,count.in.cell)
table.current.study[is.na(table.current.study)]<-"NA"
#cat("current study =",ns)
#print(table.current.study)
array.current.study<-array(data=table.current.study[,3],dim=dim.vector.all.sources[1:2],
dimnames=list(rvar.dimnames.unique,cvar.dimnames.unique))
names(dimnames(array.current.study))<-c(rvar,cvar)
#array.current.study
#IS TABLE FOR CURRENT STUDY IDENTICAL IN STRUCTURE TO EMPTY TABLE OVERALL?
etas<-as.vector(empty.table.all.sources[,1:2])
tss<-as.vector(table.current.study[,1:2])
tables.identical<-FALSE
if((sum(etas==tss))==length(etas))tables.identical<-TRUE
#if the table structure is identical to the structure of the empty table from all sources
#then simply write the counts from the study specific table to the empty table from all sources
#and then that becomes the study.specific.table for the given study
#if structure not identical match rows in study specific table to rows in array.all.sources using
#the dimnames.x.num to index the equivalent rows then the dimnames.x to check
if(tables.identical)
{
#array.all.sources[,,,ns]<-array.current.study
}
#if(!tables.identical)
{
#set up sequential numeric code for each of the sorted unique values in each dimnames
dimnames.1<-dimnames(array.all.sources)[[1]]
dimnames.1.num<-1:length(dimnames.1)
#cbind(dimnames.1,dimnames.1.num)
dimnames.2<-dimnames(array.all.sources)[[2]]
dimnames.2.num<-1:length(dimnames.2)
#cbind(dimnames.2,dimnames.2.num)
#Map row in table from current study with equivalent row in array containing unique
#values from every study and check that the identified row in the full array contains
#the same dimnames values as the row in the current study table. If it does not,
#then rather than trying to second guess all possible ways this could go wrong
#simply stop processing and ask user to work with study specific tables to
#create table statistics he/she requires
index.current.study<-rep(NA,length(table.current.study[,1]))
index.overall<-rep(NA,(dim.vector.all.sources[1]*dim.vector.all.sources[2]))
for(oo in 1:length(table.current.study[,1]))
{
d1<-table.current.study[oo,1]
n1<-dimnames.1.num[dimnames.1==d1]
d2<-table.current.study[oo,2]
n2<-dimnames.2.num[dimnames.2==d2]
index.current.study<-oo
#index.overall applies to empty.table.all.sources.col.1 etc which are all of length dim1*dim2*dim3 because
#this was created before array.all.sources was replicated to include space for all studies. So calculations
#of index.overall do not need to take account of ns value
index.overall<-n1+dim.vector.all.sources[1]*(n2-1)
# dim.vector.all.sources[1]*dim.vector.all.sources[2]*(n3-1)
count.current.study.current.row<-table.current.study[oo,3]
#check dimnames all match
d1.a<-empty.table.all.sources.col.1[index.overall]
d2.a<-empty.table.all.sources.col.2[index.overall]
#test effect of discrepency
# d1<-"999"
if(d1.a!=d1||d2.a!=d2)
{
return.message= "Dimensions of tables not behaving sensibly across studies.Please check the data in each study and calculate counts and percentages, yourself, using the counts from the individual studies"
cat(return.message)
return(return.message)
}
#dimension markers match so allocate count to correct cell
#index.overall.extended.over.all.studies applies to array.all.sources which is of length dim1*dim2*dim3*numsources
#must therefore add dim.vector.all.sources[1]*dim.vector.all.sources[2]*dim.vector.all.sources[3]*(ns-1)
#to identify correct row in extended array which has the full dimnames structure replicated for each study
index.overall.extended.over.all.studies<-index.overall+
dim.vector.all.sources[1]*dim.vector.all.sources[2]*(ns-1)
array.all.sources[index.overall.extended.over.all.studies]<-count.current.study.current.row
}
dimnames(array.all.sources)[3]<-list(as.character(1:numsources))
#print(array.all.sources)
}#end of tables not identical loop
}#end of ns loop
#Combine across studies if requested
####################################
combine.array.all.sources<-as.numeric(array.all.sources[,,1])
if(numsources>1)
{
for(ns in 2:numsources)
{
combine.array.all.sources<-combine.array.all.sources+as.numeric(array.all.sources[,,ns])
}
}
combine.array.all.sources<-array(data=combine.array.all.sources,dim=dim(array.all.sources)[1:num.table.dims],
dimnames=dimnames(array.all.sources)[1:num.table.dims])
#print(combine.array.all.sources)
######################
#return(array.all.sources)
}#end of 2 dims loop
######################################################################
#Next work with one dimensional tables
if(num.table.dims==1)
{
#identify all possible values of each dimension
rvar.dimnames<-NULL
for(ns in 1:numsources)