-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTableToLongForm.tex
More file actions
12734 lines (11027 loc) · 349 KB
/
TableToLongForm.tex
File metadata and controls
12734 lines (11027 loc) · 349 KB
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
\documentclass[a4paper]{article}
\addtolength{\oddsidemargin}{-.4in}
\addtolength{\evensidemargin}{-.4in}
\addtolength{\textwidth}{.8in}
\addtolength{\voffset}{-.8in}
\addtolength{\textheight}{1.2in}
\usepackage{noweb}
\noweboptions{english}
\usepackage{xcolor}
\usepackage[colorlinks]{hyperref}
\hypersetup{linkcolor=blue!40!black,
citecolor=green!40!black,
filecolor=cyan!40!black,
urlcolor=magenta!40!black}
\usepackage{graphicx}
\usepackage{natbib}
\begin{document}
\renewcommand\abstractname{\large Abstract}
%-----------------------------------------------------------------------
\title{\textbf{TableToLongForm}\\
Literate Program}
\author{\textit{Jimmy Oh}\\
[12pt] Department of Statistics\\
University of Auckland}
\date{}
\maketitle
\codemargin=24pt
\begin{center}
Corresponds to R Package Version 1.3.1 (release)
\end{center}
\begin{abstract}\normalsize
TableToLongForm automatically converts hierarchical Tables intended
for a human reader into a simple LongForm Dataframe that is machine
readable. It does this by recognising positional cues present in the
hierarchical Table (which would normally be interpreted visually by
the human brain) to decompose, then reconstruct the data into a
LongForm Dataframe. This is the Literate Program for TableToLongForm
and contains the entirety of the code with accompanying
documentation.
\end{abstract}
\tableofcontents
\subsection*{On Literate Programs}
\label{sec:literate.program}
This software is presented as a \emph{literate program} written in the
\emph{noweb} format (\citealt{noweb}). It serves as both the
documentation and container of the literate program. The \verb|noweb|
file can be used to produce both the \emph{literate document} and the
executable code.
The literate document is separated into \emph{documentation chunks}
and named \emph{code chunks}. Each \emph{code chunk} can contain code
directly, or contain references to other \emph{code chunks} which act
as placeholders for the contents of the respective \emph{code
chunk}. The name of each \emph{code chunk} should serve as a short
description of the code it contains. Thus each \emph{code chunk}
provides an overview of its purpose by either directly containing
code, or by containing the names of other \emph{code chunks}. The
reader is then free to delve deeper into the respective \emph{code
chunks} if desired.
\section{Introduction}
\label{sec:introduction}
This Literate Document delves deeply into the source code for
TableToLongForm. Most users will probably find the Home Page for
TableToLongForm\footnote{\url{https://www.stat.auckland.ac.nz/~joh024/Research/TableToLongForm/}}
more informative.
The Literate Program is a constant work-in-progress, and some of the
sections may have out of date documentation, or be lacking in
documentation completely.
\newpage
\section{Code Overview}
\label{sec:code.overview}
Unless the Table is horrible beyond mortal imagination, it should have
some kind of pattern, such that a human will be able to discern the
structure and hence understand the data it represents. This code
attempts to algorithmically search for such patterns, discern the
structure, then reconstruct the data into a LongForm Dataframe.
The task can be seen to consist of three phases:
\begin{itemize}
\item Phase One is Identification, which involves identifying the rows
and columns where the labels and the data can be found.
\item Phase Two is Discerning the Parentage, which involves
identifying the hierarchical structure of the data, based on the row
and column labels.
\item Phase Three is Reconstruction, where we use what we've found in
the first two phases to reconstruct the data into a LongForm
Dataframe.
\end{itemize}
\nwfilename{TableToLongForm.Rnw}\nwbegincode{1}\sublabel{RNWTab1-Tab1-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Tab1-1}}}\moddef{TableToLongForm.R~{\nwtagstyle{}\subpageref{RNWTab1-Tab1-1}}}\endmoddef\let\nwnotused=\nwoutput{}
\LA{}document header~{\nwtagstyle{}\subpageref{RNWTab1-doc3-1}}\RA{}
\LA{}Front End~{\nwtagstyle{}\subpageref{RNWTab1-Fro4-1}}\RA{}
\LA{}Back End~{\nwtagstyle{}\subpageref{RNWTab1-Bac7-1}}\RA{}
\LA{}Identification~{\nwtagstyle{}\subpageref{RNWTab1-Ide13-1}}\RA{}
\LA{}Discern Parentage~{\nwtagstyle{}\subpageref{RNWTab1-Dis30-1}}\RA{}
\LA{}Reconstruction~{\nwtagstyle{}\subpageref{RNWTab1-Rec51-1}}\RA{}
\nosublabel{RNWTab1-Tab1-1-u4}\nwnotused{TableToLongForm.R}\nwendcode{}\nwbegindocs{2}\nwdocspar
We place a document header at the top of the extracted code to
encourage people to read the literate description rather than
attempting to study the code alone.
\nwenddocs{}\nwbegincode{3}\sublabel{RNWTab1-doc3-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-doc3-1}}}\moddef{document header~{\nwtagstyle{}\subpageref{RNWTab1-doc3-1}}}\endmoddef
##----------------------------------------------------------------------
## The code in this .R file is machine generated from the literate
## program, TableToLongForm.Rnw
## Documentation can be found in the literate description for this
## program, TableToLongForm.pdf
##----------------------------------------------------------------------
\nwendcode{}\nwbegindocs{4}\nwdocspar
\subsection{Front End}
\label{sec:front.end}
The main function \verb|TableToLongForm| is defined here. For most
users this is the only function they will call. The arguments are as
follows:
\begin{description}
\item[Table] the Table to convert, given as a \verb|character matrix|.
Also accepts a \verb|data.frame|, which is coerced to a \verb|matrix|
with a warning.
\item[IdentResult] an optional \verb|list| specifying the locations of
the various elements of the \verb|Table|. By default this is
automatically generated but it can be specified manually where the
automatic detection fails.
\item[IdentPrimary, IdentAuxiliary, ParePreRow, ParePreCol] specify
the algorithms TableToLongForm should use. Refer to the respective
sections for more details.
\item[fulloutput] if \verb|TRUE|, returns a \verb|list| containing
additional information primarily useful for diagnostic
purposes. Otherwise, and by default, the function only returns the
converted \verb|data.frame| object.
\item[diagnostics] a \verb|character vector| specifying the name of
the file diagnostic output will be written to. Can also be
\verb|TRUE|, in which case the file name will be the name of the
object specified in \verb|Table|.
\item[diagnostics.trim] a \verb|logical| indicating whether the
diagnostics output should be trimmed. A good idea to keep
\verb|TRUE| (default) as trimmed output is generally more useful.
\end{description}
This function handles some busy-work, such as coercing the
\verb|Table| to a \verb|matrix| (with a warning) and setting up the
diagnostics output file. It then calls \verb|ReconsMain| which handles
the real meat of the conversion.
In the package version of TableToLongForm, this, and some back-end
functions, are the only functions that are exported, the rest are
hidden in the package namespace (which is still accessible, just not
as easily). If sourcing in the raw .R file, the majority of the
supporting functions are not hidden and can be accessed directly from
the Global Environment.
\nwenddocs{}\nwbegincode{5}\sublabel{RNWTab1-Fro4-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Fro4-1}}}\moddef{Front End~{\nwtagstyle{}\subpageref{RNWTab1-Fro4-1}}}\endmoddef
TableToLongForm =
function(Table, IdentResult = NULL,
IdentPrimary = "combound",
IdentAuxiliary = "sequence",
ParePreRow = NULL,
ParePreCol = c("mismatch", "misalign", "multirow"),
fulloutput = FALSE,
diagnostics = FALSE, diagnostics.trim = TRUE)\{
\LA{}Check Table arg~{\nwtagstyle{}\subpageref{RNWTab1-Che5-1}}\RA{}
\LA{}Setup diagnostics file~{\nwtagstyle{}\subpageref{RNWTab1-Set6-1}}\RA{}
fullout = ReconsMain(matFull = Table, IdentResult,
IdentPrimary, IdentAuxiliary, ParePreRow, ParePreCol)
if(fulloutput) fullout else fullout$datafr
\}
\nwidentuses{\\{{IdentResult}{IdentResult}}\\{{ReconsMain}{ReconsMain}}}\nwindexuse{IdentResult}{IdentResult}{RNWTab1-Fro4-1}\nwindexuse{ReconsMain}{ReconsMain}{RNWTab1-Fro4-1}\nwendcode{}\nwbegindocs{6}\nwdocspar
\nwenddocs{}\nwbegincode{7}\sublabel{RNWTab1-Che5-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Che5-1}}}\moddef{Check Table arg~{\nwtagstyle{}\subpageref{RNWTab1-Che5-1}}}\endmoddef
if(is.data.frame(Table))\{
warning("Table supplied is a data.frame.\\n",
"TableToLongForm is designed for a character matrix.\\n",
"The data.frame is being coerced to a matrix but this\\n",
"may lead to unexpected results.",
immediate. = TRUE)
Table = as.matrix(Table)
\}
if(!is.matrix(Table))
stop("Table argument must be a matrix or a data.frame")
\nwendcode{}\nwbegindocs{8}\nwdocspar
\nwenddocs{}\nwbegincode{9}\sublabel{RNWTab1-Set6-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Set6-1}}}\moddef{Setup diagnostics file~{\nwtagstyle{}\subpageref{RNWTab1-Set6-1}}}\endmoddef
if(diagnostics != FALSE)\{
if(!is.character(diagnostics))
diagnostics = deparse(substitute(Table))
assign("TCRunout", file(paste0(diagnostics, ".TCRunout"), "w"),
envir = TTLFBaseEnv)
assign("TCtrim", diagnostics.trim, envir = TTLFBaseEnv)
on.exit(\{
with(TTLFBaseEnv, \{
close(TCRunout)
rm(TCRunout)
rm(TCtrim)
\})
\})
\}
\nwidentuses{\\{{TTLFBaseEnv}{TTLFBaseEnv}}}\nwindexuse{TTLFBaseEnv}{TTLFBaseEnv}{RNWTab1-Set6-1}\nwendcode{}\nwbegindocs{10}\nwdocspar
\subsection{Back End}
\label{sec:back.end}
Various code, mainly to help produce diagnostic output, can be ignored
by most users.
\nwenddocs{}\nwbegincode{11}\sublabel{RNWTab1-Bac7-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Bac7-1}}}\moddef{Back End~{\nwtagstyle{}\subpageref{RNWTab1-Bac7-1}}}\endmoddef
\LA{}BErbinddf~{\nwtagstyle{}\subpageref{RNWTab1-BEr8-1}}\RA{}
\LA{}BEprintplist~{\nwtagstyle{}\subpageref{RNWTab1-BEp9-1}}\RA{}
\LA{}BEattrLoc~{\nwtagstyle{}\subpageref{RNWTab1-BEa10-1}}\RA{}
\LA{}BETCRsink~{\nwtagstyle{}\subpageref{RNWTab1-BET11-1}}\RA{}
\LA{}BETTLFalias~{\nwtagstyle{}\subpageref{RNWTab1-BET12-1}}\RA{}
\nwendcode{}\nwbegindocs{12}\nwdocspar
\paragraph{rbinddf}
An \verb|rbind| method to handle data.frames with differing column
names. Does not check if arguments are actually data.frames, so can
break easily.
\nwenddocs{}\nwbegincode{13}\sublabel{RNWTab1-BEr8-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-BEr8-1}}}\moddef{BErbinddf~{\nwtagstyle{}\subpageref{RNWTab1-BEr8-1}}}\endmoddef
rbinddf =
function(..., deparse.level = 0)\{
bindlist = list(...)
nameunion = NULL
for(j in 1:length(bindlist))
nameunion = union(nameunion, colnames(bindlist[[j]]))
for(j in 1:length(bindlist))\{
curdf = bindlist[[j]]
namediff = setdiff(nameunion, colnames(curdf))
matdummy = matrix(NA, nrow = nrow(curdf), ncol = length(namediff),
dimnames = list(NULL, namediff))
bindlist[[j]] = cbind(curdf, matdummy)
\}
outdf = do.call(rbind,
c(bindlist, list(deparse.level = deparse.level)))
for(j in 1:ncol(outdf))
if(mode(outdf[,j]) == "character") outdf[,j] = factor(outdf[,j])
outdf
\}
\nwindexdefn{rbinddf}{rbinddf}{RNWTab1-BEr8-1}\eatline
\nwidentdefs{\\{{rbinddf}{rbinddf}}}\nwendcode{}\nwbegindocs{14}\nwdocspar
\paragraph{print.plist}
A print method for class \verb|plist|, which are nested lists with a
numeric vector at the lowest level; \verb|print.default| is rather
inefficient in displaying such nested lists.
\nwenddocs{}\nwbegincode{15}\sublabel{RNWTab1-BEp9-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-BEp9-1}}}\moddef{BEprintplist~{\nwtagstyle{}\subpageref{RNWTab1-BEp9-1}}}\endmoddef
print.plist =
function(x, ...)\{
plistC = function(plist)\{
pLoc = attr(plist, "Loc")
if(is.list(plist))\{
namevec = names(plist)
if(!is.null(pLoc))
namevec = paste0(names(plist),
" (", pLoc[,"rows"], ", ", pLoc[,"cols"], ")")
namelist = as.list(namevec)
for(i in 1:length(namelist))
namelist[[i]] =
c(paste("+", namelist[[i]]),
paste("-", plistC(plist[[i]])))
do.call(c, namelist)
\} else\{
if(!is.null(names(plist)))\{
namevec = names(plist)
if(!is.null(pLoc))
namevec = paste0(names(plist),
" (", plist, ", ", pLoc[,"cols"], ")")
paste("+", namevec)
\} else paste(plist, collapse = " ")
\}
\}
cat(plistC(x), sep = "\\n")
\}
\nwendcode{}\nwbegindocs{16}\nwdocspar
\paragraph{attrLoc}
A function for creating a \verb|plist| object and binding location
information (rows and cols) to it.
\nwenddocs{}\nwbegincode{17}\sublabel{RNWTab1-BEa10-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-BEa10-1}}}\moddef{BEattrLoc~{\nwtagstyle{}\subpageref{RNWTab1-BEa10-1}}}\endmoddef
attrLoc =
function(plist, rows = NULL, cols = NULL)\{
attr(plist, "Loc") = cbind(rows, cols)
class(plist) = "plist"
plist
\}
\nwindexdefn{attrLoc}{attrLoc}{RNWTab1-BEa10-1}\eatline
\nwidentdefs{\\{{attrLoc}{attrLoc}}}\nwendcode{}\nwbegindocs{18}\nwdocspar
\paragraph{TCRsink}
Sinks the output to \verb|TCRunout| for diagnostic output. Requires
the existence of \verb|TCRunout| which is created by the main function
\verb|TableToLongForm| when \verb|diagnostics = TRUE|.
Spaces may be introduced by \verb|match.call|, thus any spaces in the
args of \emph{variables to sink} (that is, the arguments supplied via
\verb|...|) are removed without warning.
We also create the \verb|TTLFBaseEnv| here, which is currently only
used to temporarily store \verb|TCRunout|.
\nwenddocs{}\nwbegincode{19}\sublabel{RNWTab1-BET11-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-BET11-1}}}\moddef{BETCRsink~{\nwtagstyle{}\subpageref{RNWTab1-BET11-1}}}\endmoddef
TCRsink =
function(ID, ...)
if(exists("TCRunout", envir = TTLFBaseEnv))\{
varlist = list(...)
names(varlist) = gsub(" ", "", as.character(match.call()[-(1:2)]))
TCtrim = get("TCtrim", envir = TTLFBaseEnv)
with(TTLFBaseEnv, sink(TCRunout))
for(i in 1:length(varlist))\{
cat("###TCR", ID, names(varlist)[i], "\\n")
curvar = varlist[[i]]
if(TCtrim == TRUE)\{
curvar = head(curvar)
if(is.matrix(curvar) || is.matrix(curvar))
if(ncol(curvar) > 6)
curvar = curvar[,1:6]
\}
print(curvar)
\}
sink()
\}
TTLFBaseEnv = new.env()
\nwindexdefn{TCRsink}{TCRsink}{RNWTab1-BET11-1}\nwindexdefn{TTLFBaseEnv}{TTLFBaseEnv}{RNWTab1-BET11-1}\eatline
\nwidentdefs{\\{{TCRsink}{TCRsink}}\\{{TTLFBaseEnv}{TTLFBaseEnv}}}\nwendcode{}\nwbegindocs{20}\nwdocspar
\paragraph{TTLFalias}
Used for the new Modular System. Check ``Working with Modules''
documentation available from the main website.
Should add a check to aliasAdd for existing rows with same alias (and
same Type, probably ok to allow same alias for different Types).
\nwenddocs{}\nwbegincode{21}\sublabel{RNWTab1-BET12-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-BET12-1}}}\moddef{BETTLFalias~{\nwtagstyle{}\subpageref{RNWTab1-BET12-1}}}\endmoddef
with(TTLFBaseEnv, \{aliasmat = NULL\})
TTLFaliasAdd =
function(Type, Fname, Falias, Author = "", Description = "")
assign("aliasmat",
rbind(get("aliasmat", envir = TTLFBaseEnv),
c(Type = Type, Name = Fname, Alias = Falias,
Author = Author, Description = Description)),
envir = TTLFBaseEnv)
TTLFaliasGet =
function(Type, Falias)\{
aliasmat = get("aliasmat", envir = TTLFBaseEnv)
matchRow = which(aliasmat[,"Type"] == Type &
aliasmat[,"Alias"] == Falias)
if(length(matchRow) == 1)
aliasmat[matchRow,"Name"]
else stop("Invalid algorithm specified for ", Type)
\}
TTLFaliasList =
function()\{
aliasmat = get("aliasmat", envir = TTLFBaseEnv)
Types = unique(aliasmat[,"Type"])
for(Type in Types)\{
cat("==Type: ", Type, "==\\n", sep = "")
Algos = aliasmat[aliasmat[,"Type"] == Type,,drop=FALSE]
for(i in 1:nrow(Algos))
cat("Name: ", Algos[i, "Name"], "\\n",
"Alias: ", Algos[i, "Alias"], "\\n",
"Author: ", Algos[i, "Author"], "\\n",
"Description: ", Algos[i, "Description"], "\\n\\n",
sep = "")
\}
\}
\nwindexdefn{TTLFaliasAdd}{TTLFaliasAdd}{RNWTab1-BET12-1}\nwindexdefn{TTLFaliasGet}{TTLFaliasGet}{RNWTab1-BET12-1}\eatline
\nwidentdefs{\\{{TTLFaliasAdd}{TTLFaliasAdd}}\\{{TTLFaliasGet}{TTLFaliasGet}}}\nwidentuses{\\{{TTLFBaseEnv}{TTLFBaseEnv}}}\nwindexuse{TTLFBaseEnv}{TTLFBaseEnv}{RNWTab1-BET12-1}\nwendcode{}\nwbegindocs{22}\nwdocspar
\section{Identification}
\label{sec:identification}
The purpose of \textbf{Identification} is to identify where in the
Table the data is found and where the accompanying labels are, while
ignoring any extraneous information we do not want. The output is the
\verb|IdentResult|, a list containing two elements, \verb|rows| and
\verb|cols|, each of which is a list containing these two elements:
\begin{description}
\item[label] - a vector of the rows or columns where the labels are
found.
\item[data] - a vector of the rows or columns where the data are
found.
\end{description}
It is intended for this procedure to involve a number of
Identification algorithms that are used for a high degree of
reliability and flexibility, but at this stage there is only a single
Primary algorithm, supplemented by a single Auxiliary algorithm.
We separate the Identification functions into three groups.
\begin{description}
\item[Ident Primary] contain Primary Ident algorithms, of which one is
chosen when calling \verb|TableToLongForm|.
\item[Ident Auxiliary] contain Auxiliary Ident algorithms, of which
any combination, in any order, can be chosen when calling
\verb|TableToLongForm|. They are called after the Primary algorithm,
to refine the \verb|IdentResult|.
\item[Ident Support] contains supporting functions called by the
Primary and Auxiliary functions.
\end{description}
\nwenddocs{}\nwbegincode{23}\sublabel{RNWTab1-Ide13-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ide13-1}}}\moddef{Identification~{\nwtagstyle{}\subpageref{RNWTab1-Ide13-1}}}\endmoddef
\LA{}Ident Primary~{\nwtagstyle{}\subpageref{RNWTab1-Ide14-1}}\RA{}
\LA{}Ident Auxiliary~{\nwtagstyle{}\subpageref{RNWTab1-Ide20-1}}\RA{}
\LA{}Ident Support~{\nwtagstyle{}\subpageref{RNWTab1-Ide24-1}}\RA{}
\nwendcode{}\nwbegindocs{24}\nwdocspar
\subsection{Identification - Primary}
The Primary Ident algorithms should take a single argument,
\verb|matFull|. They should return an \verb|IdentResult|.
\label{sec:IdentPrimary}
\nwenddocs{}\nwbegincode{25}\sublabel{RNWTab1-Ide14-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ide14-1}}}\moddef{Ident Primary~{\nwtagstyle{}\subpageref{RNWTab1-Ide14-1}}}\endmoddef
\LA{}Ident by Most Common Boundary~{\nwtagstyle{}\subpageref{RNWTab1-Ide15-1}}\RA{}
\nwendcode{}\nwbegindocs{26}\nwdocspar
\subsubsection{Ident by Most Common Boundary}
Search for the most common start and end rows and columns (the
boundary) to find a block (rectangular region) of numbers, which is
assumed to be our table of data.
\nwenddocs{}\nwbegincode{27}\sublabel{RNWTab1-Ide15-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ide15-1}}}\moddef{Ident by Most Common Boundary~{\nwtagstyle{}\subpageref{RNWTab1-Ide15-1}}}\endmoddef
IdentbyMostCommonBoundary =
function(matFull)\{
\LA{}Get Non empty rows and cols~{\nwtagstyle{}\subpageref{RNWTab1-Get16-1}}\RA{}
\LA{}Call Ident MostCommonBoundary~{\nwtagstyle{}\subpageref{RNWTab1-Cal17-1}}\RA{}
\LA{}Construct rowslist and colslist~{\nwtagstyle{}\subpageref{RNWTab1-Con18-1}}\RA{}
\LA{}Cleanup MostCommonBoundary Results~{\nwtagstyle{}\subpageref{RNWTab1-Cle19-1}}\RA{}
list(rows = rowslist, cols = colslist)
\}
TTLFaliasAdd("IdentPrimary", "IdentbyMostCommonBoundary", "combound",
"Base Algorithm", "Default IdentPrimary algorithm")
\nwidentuses{\\{{TTLFaliasAdd}{TTLFaliasAdd}}}\nwindexuse{TTLFaliasAdd}{TTLFaliasAdd}{RNWTab1-Ide15-1}\nwendcode{}\nwbegindocs{28}\nwdocspar
\nwenddocs{}\nwbegincode{29}\sublabel{RNWTab1-Get16-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Get16-1}}}\moddef{Get Non empty rows and cols~{\nwtagstyle{}\subpageref{RNWTab1-Get16-1}}}\endmoddef
rowNonempty = (1:nrow(matFull))[IdentNonEmpty(matFull, 1)]
colNonempty = (1:ncol(matFull))[IdentNonEmpty(matFull, 2)]
\nwidentuses{\\{{IdentNonEmpty}{IdentNonEmpty}}}\nwindexuse{IdentNonEmpty}{IdentNonEmpty}{RNWTab1-Get16-1}\nwendcode{}\nwbegindocs{30}\nwdocspar
\nwenddocs{}\nwbegincode{31}\sublabel{RNWTab1-Cal17-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Cal17-1}}}\moddef{Call Ident MostCommonBoundary~{\nwtagstyle{}\subpageref{RNWTab1-Cal17-1}}}\endmoddef
rowData = IdentMostCommonBoundary(matFull, 2)
colData = IdentMostCommonBoundary(matFull, 1)
TCRsink("CIMCB", rowData, colData)
\nwidentuses{\\{{IdentMostCommonBoundary}{IdentMostCommonBoundary}}\\{{TCRsink}{TCRsink}}}\nwindexuse{IdentMostCommonBoundary}{IdentMostCommonBoundary}{RNWTab1-Cal17-1}\nwindexuse{TCRsink}{TCRsink}{RNWTab1-Cal17-1}\nwendcode{}\nwbegindocs{32}\nwdocspar
Example values for \textbf{ToyExComplete.csv} \texttt{(ID: CIMCB)}
\begin{verbatim}
> rowData
[1] 5 14
\end{verbatim}
\begin{verbatim}
> colData
[1] 4 11
\end{verbatim}
\vspace{-1.5em}
\noindent\rule{0.25\textwidth}{0.4pt}
\vspace{0.5em}
We construct the interim \verb|rowslist| taking every non-empty row
before the most common start of the numbers block (\verb|rowData[1]|)
and assigning these to the \verb|label| region. The numbers block
(which is bounded by \verb|rowData[1]| and \verb|rowData[2]|) is
assigned to the \verb|data| region. The interim \verb|colslist| is
constructed in the same manner.
\nwenddocs{}\nwbegincode{33}\sublabel{RNWTab1-Con18-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Con18-1}}}\moddef{Construct rowslist and colslist~{\nwtagstyle{}\subpageref{RNWTab1-Con18-1}}}\endmoddef
rowslist = list(label = rowNonempty[rowNonempty < rowData[1]],
data = rowNonempty[(rowNonempty >= rowData[1]) &
(rowNonempty <= rowData[2])])
colslist = list(label = colNonempty[colNonempty < colData[1]],
data = colNonempty[(colNonempty >= colData[1]) &
(colNonempty <= colData[2])])
TCRsink("CRAC", rowslist, colslist)
\nwidentuses{\\{{TCRsink}{TCRsink}}}\nwindexuse{TCRsink}{TCRsink}{RNWTab1-Con18-1}\nwendcode{}\nwbegindocs{34}\nwdocspar
Example values for \textbf{ToyExComplete.csv} \texttt{(ID: CRAC)}
\begin{verbatim}
> rowslist
$label
[1] 1 2 3 4
$data
[1] 5 6 7 8 9 10 11 12 13 14
\end{verbatim}
\begin{verbatim}
> colslist
$label
[1] 1 2
$data
[1] 4 5 6 7 8 9 10 11
\end{verbatim}
\vspace{-1.5em}
\noindent\rule{0.25\textwidth}{0.4pt}
\vspace{0.5em}
As the \verb|MostCommonBoundary| algorithm searches for the data
region, it can be conservative with respect to the rows and columns
assigned to data. Under most circumstances this causes no problems,
but in certain rare cases of mismatched column labels, there are
column labels that are outside the data region (that is, the column
label is not over the data it is the label of, hence mismatched).
To correct for this, we do the following:
\begin{enumerate}
\item If \verb|matRowLabel| isn't all empty
\item Shift any fully empty columns on the right to \verb|cols$data|
\end{enumerate}
\nwenddocs{}\nwbegincode{35}\sublabel{RNWTab1-Cle19-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Cle19-1}}}\moddef{Cleanup MostCommonBoundary Results~{\nwtagstyle{}\subpageref{RNWTab1-Cle19-1}}}\endmoddef
matRowLabel = matFull[rowslist$data, colslist$label,drop=FALSE]
if(!all(is.na(matRowLabel)) && ncol(matRowLabel) > 1)\{
RowLabelNonempty = IdentNonEmpty(matRowLabel, 2)
if(max(RowLabelNonempty) < ncol(matRowLabel))\{
toshift = (max(RowLabelNonempty) + 1):ncol(matRowLabel)
colslist$data = c(colslist$label[toshift], colslist$data)
colslist$label = colslist$label[-toshift]
\}
\}
\nwidentuses{\\{{IdentNonEmpty}{IdentNonEmpty}}}\nwindexuse{IdentNonEmpty}{IdentNonEmpty}{RNWTab1-Cle19-1}\nwendcode{}\nwbegindocs{36}\nwdocspar
\subsection{Identification - Auxiliary}
The Auxiliary Ident algorithms should take two arguments,
\verb|matFull| and \verb|IdentResult|. They should return an
\verb|IdentResult|.
\label{sec:IdentAuxiliary}
\nwenddocs{}\nwbegincode{37}\sublabel{RNWTab1-Ide20-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ide20-1}}}\moddef{Ident Auxiliary~{\nwtagstyle{}\subpageref{RNWTab1-Ide20-1}}}\endmoddef
\LA{}Ident by Sequence~{\nwtagstyle{}\subpageref{RNWTab1-Ide21-1}}\RA{}
\nwendcode{}\nwbegindocs{38}\nwdocspar
\subsubsection{Ident by Sequence}
Search for fully numeric row labels (e.g. Years) that were
misidentified as data, by checking if the numbers follow some fixed
sequence. If such a situation is found (result is not \verb|NA|), we
update \verb|IdentResult|. This is intended to be used in conjunction
with the \emph{Ident by Most Common Boundary} Primary algorithm, which
assumes numbers to be data, and not labels.
Currently the algorithm is conservative, only making the check if the
current \verb|matRowLabel| is empty (\verb|ncol = 0|, or all
\verb|NA|s), and only accepting a sequence of fixed difference, with
no gaps or jumps, e.g.
\begin{itemize}
\item 1 2 3 4, then a sequence
\item 1 2 4 5, then not a sequence
\end{itemize}
\nwenddocs{}\nwbegincode{39}\sublabel{RNWTab1-Ide21-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ide21-1}}}\moddef{Ident by Sequence~{\nwtagstyle{}\subpageref{RNWTab1-Ide21-1}}}\endmoddef
IdentbySequence =
function(matFull, IdentResult)
with(IdentResult, \{
matRowLabel = matFull[rows$data, cols$label]
\LA{}If empty take next column~{\nwtagstyle{}\subpageref{RNWTab1-Ife22-1}}\RA{}
\LA{}Check if sequence~{\nwtagstyle{}\subpageref{RNWTab1-Che23-1}}\RA{}
\})
TTLFaliasAdd("IdentAuxiliary", "IdentbySequence", "sequence",
"Base Algorithm", paste("Search for fully numeric row",
"labels (e.g. Years) that were misidentified as data"))
\nwidentuses{\\{{IdentResult}{IdentResult}}\\{{TTLFaliasAdd}{TTLFaliasAdd}}}\nwindexuse{IdentResult}{IdentResult}{RNWTab1-Ide21-1}\nwindexuse{TTLFaliasAdd}{TTLFaliasAdd}{RNWTab1-Ide21-1}\nwendcode{}\nwbegindocs{40}\nwdocspar
\nwenddocs{}\nwbegincode{41}\sublabel{RNWTab1-Ife22-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ife22-1}}}\moddef{If empty take next column~{\nwtagstyle{}\subpageref{RNWTab1-Ife22-1}}}\endmoddef
if(all(is.na(matRowLabel)))\{
cols$label = cols$data[1]
cols$data = cols$data[-1]
IdentbySequence(matFull, list(rows = rows, cols = cols))
\}
\nwendcode{}\nwbegindocs{42}\nwdocspar
Check to see if all diffs are equal, but original values are not. If
it is, we have a sequence and we return an updated \verb|IdentResult|.
\nwenddocs{}\nwbegincode{43}\sublabel{RNWTab1-Che23-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Che23-1}}}\moddef{Check if sequence~{\nwtagstyle{}\subpageref{RNWTab1-Che23-1}}}\endmoddef
else\{
matRowLabel = suppressWarnings(as.numeric(matRowLabel))
if(length(unique(matRowLabel)) > 1 &&
length(unique(diff(matRowLabel))) == 1)
list(rows = rows, cols = cols)
else IdentResult
\}
\nwidentuses{\\{{IdentResult}{IdentResult}}}\nwindexuse{IdentResult}{IdentResult}{RNWTab1-Che23-1}\nwendcode{}\nwbegindocs{44}\nwdocspar
\subsection{Identification - Support}
\label{sec:IdentSupport}
Here we discuss the supporting functions called by the Primary and
Auxiliary functions. Each chunk corresponds to a separate supporting
function.
\nwenddocs{}\nwbegincode{45}\sublabel{RNWTab1-Ide24-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ide24-1}}}\moddef{Ident Support~{\nwtagstyle{}\subpageref{RNWTab1-Ide24-1}}}\endmoddef
\LA{}Ident Non Empty~{\nwtagstyle{}\subpageref{RNWTab1-Ide25-1}}\RA{}
\LA{}Ident Pattern~{\nwtagstyle{}\subpageref{RNWTab1-Ide26-1}}\RA{}
\LA{}Ident Most Common Boundary~{\nwtagstyle{}\subpageref{RNWTab1-Ide29-1}}\RA{}
\nwendcode{}\nwbegindocs{46}\nwdocspar
\subsubsection{IdentNonEmpty}
Given a matrix (\verb|mat|) and a margin (1 for rows, 2 for
columns), return a vector giving the indices of non-empty rows or
columns. Can specify a different empty identifying function (default
\verb|is.na|). Procedure:
\begin{enumerate}
\item Compute \verb|isnonempty|, a logical vector about whether the
rows or cols are not empty.
\item Use \verb|which| on \verb|isnonempty| to get indices.
\end{enumerate}
\nwenddocs{}\nwbegincode{47}\sublabel{RNWTab1-Ide25-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ide25-1}}}\moddef{Ident Non Empty~{\nwtagstyle{}\subpageref{RNWTab1-Ide25-1}}}\endmoddef
IdentNonEmpty =
function(mat, margin, emptyident = is.na)\{
isnonempty = apply(mat, margin, function(x) !all(emptyident(x)))
which(isnonempty)
\}
\nwindexdefn{IdentNonEmpty}{IdentNonEmpty}{RNWTab1-Ide25-1}\eatline
\nwidentdefs{\\{{IdentNonEmpty}{IdentNonEmpty}}}\nwendcode{}\nwbegindocs{48}\nwdocspar
\subsubsection{IdentPattern}
Attempt to discern a repeating pattern in \verb|vec|, which can be a
vector of any type (which is coerced to \verb|character|). The
returned value is the grouping number for the repeating pattern, or
the length of \verb|vec| if there is no repeating pattern, e.g.
\begin{itemize}
\item \verb|vec| = 1 1 1 1, then return 1
\item \verb|vec| = 3 4 3 4, then return 2
\item \verb|vec| = 1 2 3 4, then return 4
\item \verb|vec| = 1 2 3 1, then return 4
\end{itemize}
\verb|IdentPattern| does this fairly efficiently by use of regular
expressions and \verb|match|.
\nwenddocs{}\nwbegincode{49}\sublabel{RNWTab1-Ide26-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ide26-1}}}\moddef{Ident Pattern~{\nwtagstyle{}\subpageref{RNWTab1-Ide26-1}}}\endmoddef
IdentPattern =
function(vec)\{
\LA{}Look for potential repeat~{\nwtagstyle{}\subpageref{RNWTab1-Loo27-1}}\RA{}
\LA{}Check if pattern repeats~{\nwtagstyle{}\subpageref{RNWTab1-Che28-1}}\RA{}
\}
\nwindexdefn{IdentPattern}{IdentPattern}{RNWTab1-Ide26-1}\eatline
\nwidentdefs{\\{{IdentPattern}{IdentPattern}}}\nwendcode{}\nwbegindocs{50}\nwdocspar
Look for when unique values of \verb|vec| repeat, and see if the
distance (\verb|diff|) between these are equal (hence the
\verb|unique| of the \verb|diff| result will be of length 1). If it
is, we take this as our potential repeating point and move on.
If the value does not repeat at all, \verb|diff| will return a
\verb|vector| of length 0, which is adjusted to the length of
\verb|vec|.
\nwenddocs{}\nwbegincode{51}\sublabel{RNWTab1-Loo27-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Loo27-1}}}\moddef{Look for potential repeat~{\nwtagstyle{}\subpageref{RNWTab1-Loo27-1}}}\endmoddef
matchvec = match(vec, unique(vec))
for(i in 1:length(unique(matchvec)))\{
repind = unique(diff(which(matchvec == i)))
if(length(repind) == 0)
repind = length(vec)
if(length(repind) == 1)
break
\}
\nwendcode{}\nwbegindocs{52}\nwdocspar
We combine the first \verb|repind| elements of \verb|vec| and collapse
this into a single string. A \verb|grep| is then called on the entire
\verb|vec| that has also been collapsed into a single string, checking
to see if the entire string can be matched to some repeat of the
aforementioned collapsed string of the first \verb|repind|
elements. If it can, we have a repeating pattern and thus return
\verb|repind|. Otherwise, we return the length of \verb|vec|.
\nwenddocs{}\nwbegincode{53}\sublabel{RNWTab1-Che28-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Che28-1}}}\moddef{Check if pattern repeats~{\nwtagstyle{}\subpageref{RNWTab1-Che28-1}}}\endmoddef
curseg = paste0("^(", paste(vec[1:repind], collapse = ""), ")+$")
if(length(grep(curseg, paste(vec, collapse = ""))) > 0)
repind else length(vec)
\nwendcode{}\nwbegindocs{54}\nwdocspar
\subsubsection{IdentMostCommonBoundary}
Search for the most common first and last rows/cols to identify a
block (rectangular region) of numbers. Procedure:
\begin{enumerate}
\item Suppose \verb|margin = 2|, then loop through each column and
search for cells containing numbers.
\item Compute the first row with a number for each column
(\verb|nstarts|), and do the same for the last row (\verb|nends|).
\item Return the most common first and last rows.
\end{enumerate}
\nwenddocs{}\nwbegincode{55}\sublabel{RNWTab1-Ide29-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ide29-1}}}\moddef{Ident Most Common Boundary~{\nwtagstyle{}\subpageref{RNWTab1-Ide29-1}}}\endmoddef
IdentMostCommonBoundary =
function(matFull, margin)\{
isnumber = suppressWarnings(apply(matFull, margin,
function(x) which(!is.na(as.numeric(x)))))
nstarts = table(sapply(isnumber,
function(x) if(length(x) > 0) min(x) else NA))
nends = table(sapply(isnumber,
function(x) if(length(x) > 0) max(x) else NA))
as.numeric(names(c(which.max(nstarts), which.max(rev(nends)))))
\}
\nwindexdefn{IdentMostCommonBoundary}{IdentMostCommonBoundary}{RNWTab1-Ide29-1}\eatline
\nwidentdefs{\\{{IdentMostCommonBoundary}{IdentMostCommonBoundary}}}\nwendcode{}\nwbegindocs{56}\nwdocspar
\section{Discern Parentage}
\label{sec:parentage}
The purpose of \textbf{Discern Parentage} is to understand the
hierarchical structure (the \emph{parentage}) of the row and column
labels. The output will be the \verb|rowplist| and \verb|colplist|,
the row and column parentage lists. TO DO explanation of plist.
We separate the Parentage functions into five groups.
\begin{description}
\item[Pare Pre Row] contain pre-requisite algorithms that tidy up the
Row Labels for correct operation of the Main Parentage
algorithm. Any combination of these algorithms, in any order, can be
chosen when calling \verb|TableToLongForm|. The current
implementation of TableToLongForm has no Pre Row algorithms.
\item[Pare Pre Col] contain pre-requisite algorithms that tidy up the
Column Labels for correct operation of the Main Parentage
algorithm. Any combination of these algorithms, in any order, can be
chosen when calling \verb|TableToLongForm|.
\item[Pare Front] is a simple `front-end' function that makes the
appropriate first call to \verb|PareMain|.
\item[Pare Main] contains the Main algorithm that will recursively
call itself until the all parentage is discerned.
\item[Pare Low Level] contains low-level functions called by the Main
function.
\end{description}
\nwenddocs{}\nwbegincode{57}\sublabel{RNWTab1-Dis30-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Dis30-1}}}\moddef{Discern Parentage~{\nwtagstyle{}\subpageref{RNWTab1-Dis30-1}}}\endmoddef
\LA{}Pare Pre Row~{\nwtagstyle{}\subpageref{RNWTab1-Par31-1}}\RA{}
\LA{}Pare Pre Col~{\nwtagstyle{}\subpageref{RNWTab1-Par32-1}}\RA{}
\LA{}Pare Front~{\nwtagstyle{}\subpageref{RNWTab1-Par38-1}}\RA{}
\LA{}Pare Main~{\nwtagstyle{}\subpageref{RNWTab1-Par39-1}}\RA{}
\LA{}Pare Low Level~{\nwtagstyle{}\subpageref{RNWTab1-Par45-1}}\RA{}
\nwendcode{}\nwbegindocs{58}\nwdocspar
\subsection{Parentage - Pre Row}
Parentage Pre Row algorithms should take two arguments, \verb|matData|
and \verb|matRowLabel|. They should return a named list containing two
elements, \verb|matData| and \verb|matRowLabel|.
The current implementation of TableToLongForm has no Pre Row
algorithms, but has support for external modules that add Pre Row
algorithms.
\nwenddocs{}\nwbegincode{59}\sublabel{RNWTab1-Par31-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Par31-1}}}\moddef{Pare Pre Row~{\nwtagstyle{}\subpageref{RNWTab1-Par31-1}}}\endmoddef
## Empty
\nwendcode{}\nwbegindocs{60}\nwdocspar
\subsection{Parentage - Pre Col}
Parentage Pre Col algorithms should take two arguments, \verb|matData|
and \verb|matColLabel|. They should return a named list containing two
elements, \verb|matData| and \verb|matColLabel|.
\nwenddocs{}\nwbegincode{61}\sublabel{RNWTab1-Par32-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Par32-1}}}\moddef{Pare Pre Col~{\nwtagstyle{}\subpageref{RNWTab1-Par32-1}}}\endmoddef
\LA{}Mismatched Col Labels~{\nwtagstyle{}\subpageref{RNWTab1-Mis33-1}}\RA{}
\LA{}Misaligned Col Parent~{\nwtagstyle{}\subpageref{RNWTab1-Mis34-1}}\RA{}
\LA{}Multirow Col Labels~{\nwtagstyle{}\subpageref{RNWTab1-Mul37-1}}\RA{}
\nwendcode{}\nwbegindocs{62}\nwdocspar
\subsubsection{Case Mismatched Column Labels}
We check for any mismatched column labels by checking if there are the
same number of non-empty columns for the two subsets, and that there
are empty columns in the subsets, which together imply mismatched
column labels. If that is the case, we update our mat Subsets as
required.
\begin{table}[hbt]
\hspace{7em}
\begin{tabular}{| l | l |}
\hline
Column Label & \\
\hline
& 1 \\
& 2 \\
& 3 \\
\hline
\end{tabular}
\hspace{10em}
\begin{tabular}{| p{1.5em} | l |}
\hline
\multicolumn{2}{| c |}{Column Label} \\
\hline
& 1 \\
& 2 \\
& 3 \\
\hline
\end{tabular}
\caption{An example of mismatched column labels. The label is in a
different column to the data it belongs to. The algorithm can
detect this as mismatched as they have the same number of
non-empty columns (1), and have empty columns in each subset (seen
easily in the left table as the 2 empty cells). Such cases can
occur due to some misguided attempts to visually align the label
to the data (e.g. table on the right).}
\end{table}
\nwenddocs{}\nwbegincode{63}\sublabel{RNWTab1-Mis33-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Mis33-1}}}\moddef{Mismatched Col Labels~{\nwtagstyle{}\subpageref{RNWTab1-Mis33-1}}}\endmoddef
ParePreColMismatch =
function(matData, matColLabel)\{
colsData = IdentNonEmpty(matData, 2)
colsLabels = IdentNonEmpty(matColLabel, 2)
if(length(colsData) == length(colsLabels))
if(ncol(matData) != length(colsData))\{
matColLabel = matColLabel[,colsLabels,drop=FALSE]
matData = matData[,colsData,drop=FALSE]
\}
list(matData = matData, matColLabel = matColLabel)
\}
TTLFaliasAdd("ParePreCol", "ParePreColMismatch", "mismatch",
"Base Algorithm", paste("Correct for column labels",
"not matched correctly over data (label in a",
"different column to data)"))
\nwidentuses{\\{{IdentNonEmpty}{IdentNonEmpty}}\\{{TTLFaliasAdd}{TTLFaliasAdd}}}\nwindexuse{IdentNonEmpty}{IdentNonEmpty}{RNWTab1-Mis33-1}\nwindexuse{TTLFaliasAdd}{TTLFaliasAdd}{RNWTab1-Mis33-1}\nwendcode{}\nwbegindocs{64}\nwdocspar
\subsubsection{Case Misaligned Column Parents}
We correct for any misaligned column parents by using pattern matching
to detect parent-groupings, and then realigning the parents.
\nwenddocs{}\nwbegincode{65}\sublabel{RNWTab1-Mis34-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Mis34-1}}}\moddef{Misaligned Col Parent~{\nwtagstyle{}\subpageref{RNWTab1-Mis34-1}}}\endmoddef
ParePreColMisaligned =
function(matData, matColLabel)\{
TCRsink("MCPBefore", matColLabel)
for(i in 1:nrow(matColLabel))\{
currow = matColLabel[i,]
\LA{}Search for Pattern~{\nwtagstyle{}\subpageref{RNWTab1-Sea35-1}}\RA{}
\LA{}Align Column Parents~{\nwtagstyle{}\subpageref{RNWTab1-Ali36-1}}\RA{}
\}
TCRsink("MCPAfter", matColLabel)
list(matData = matData, matColLabel = matColLabel)
\}
TTLFaliasAdd("ParePreCol", "ParePreColMisaligned", "misalign",
"Base Algorithm", paste("Correct for column labels",
"not aligned correctly over data (parents not",
"positioned on the far-left, relative to their",
"children in the row below)"))
\nwidentuses{\\{{TCRsink}{TCRsink}}\\{{TTLFaliasAdd}{TTLFaliasAdd}}}\nwindexuse{TCRsink}{TCRsink}{RNWTab1-Mis34-1}\nwindexuse{TTLFaliasAdd}{TTLFaliasAdd}{RNWTab1-Mis34-1}\nwendcode{}\nwbegindocs{66}\nwdocspar
Example values for \textbf{ToyExComplete.csv} \texttt{(ID: MCPBefore)}
\begin{verbatim}
> matColLabel
V4 V5 V6 V7 V8 V9
[1,] NA NA NA NA NA NA
[2,] NA "Col Parent1" NA NA NA "Col Parent2"
[3,] "Col" "Col" "Col" "Col" "Col" "Col"
[4,] "Child1" "Child2" "Child3" "Child4" "Child1" "Child2"
\end{verbatim}
\vspace{-1.5em}
\noindent\rule{0.25\textwidth}{0.4pt}
\vspace{0.5em}
%TCEx MCPAfter matColLabel
%TCEx MCPBefore matColLabel
Example values for \textbf{ToyExComplete.csv} \texttt{(ID: MCPAfter)}
\begin{verbatim}
> matColLabel
V4 V5 V6 V7 V8 V9
[1,] NA NA NA NA NA NA
[2,] "Col Parent1" NA NA NA "Col Parent2" NA
[3,] "Col" "Col" "Col" "Col" "Col" "Col"
[4,] "Child1" "Child2" "Child3" "Child4" "Child1" "Child2"
\end{verbatim}
\vspace{-1.5em}
\noindent\rule{0.25\textwidth}{0.4pt}
\vspace{0.5em}
\begin{table}[hbt]
\centering
\begin{tabular}{| l | l | l | l | l | l |}
\hline
& Column Parent1 & & & Column Parent2 & \\
\hline
Child1 & Child2 & Child3 &
Child1 & Child2 & Child3 \\
\hline
\end{tabular}
\caption{An example of misaligned column parents. For our low-level
Parentage algorithm to work, we want the Column Parents to be in
the left-most cell of their parent-grouping.}
\label{tab:Pare.misaligned}
\end{table}
The value of \verb|curPattern| will be the following:
\begin{itemize}
\item If completely empty (all \verb|NA|), return \verb|NA|.
\item If any empty, check pattern of emptiness. In the above Table row
1, this will find the pattern: NonEmpty-Empty-NonEmpty which occurs
twice. Hence return 2.
\item Else, all cells are non-empty, check pattern of contents. In the
above Table row 2, this will find the pattern: Child1-Child2-Child3
which occurs twice. Hence return 2.
\end{itemize}
\nwenddocs{}\nwbegincode{67}\sublabel{RNWTab1-Sea35-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Sea35-1}}}\moddef{Search for Pattern~{\nwtagstyle{}\subpageref{RNWTab1-Sea35-1}}}\endmoddef
curPattern =
if(all(is.na(currow))) NA
else if(any(is.na(currow))) IdentPattern(is.na(currow))
else IdentPattern(currow)
\nwidentuses{\\{{IdentPattern}{IdentPattern}}}\nwindexuse{IdentPattern}{IdentPattern}{RNWTab1-Sea35-1}\nwendcode{}\nwbegindocs{68}\nwdocspar
For each subset of the row (based on pattern), move any empty cells
(\verb|NA|) to the end, hence aligning the non-empty cell (the parent)
to the left.
\nwenddocs{}\nwbegincode{69}\sublabel{RNWTab1-Ali36-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Ali36-1}}}\moddef{Align Column Parents~{\nwtagstyle{}\subpageref{RNWTab1-Ali36-1}}}\endmoddef
if(!is.na(curPattern))\{
nParents = length(currow)/curPattern
for(j in 1:nParents)\{
curcols = 1:curPattern + curPattern * (j - 1)
cursub = currow[curcols]
currow[curcols] = c(cursub[!is.na(cursub)], cursub[is.na(cursub)])
TCRsink("ACP", cursub, currow[curcols])
\}
matColLabel[i,] = currow
\}
\nwidentuses{\\{{TCRsink}{TCRsink}}}\nwindexuse{TCRsink}{TCRsink}{RNWTab1-Ali36-1}\nwendcode{}\nwbegindocs{70}\nwdocspar
Example values for \textbf{ToyExComplete.csv} \texttt{(ID: ACP)}
\begin{verbatim}
> cursub
V4 V5 V6 V7
NA "Col Parent1" NA NA
\end{verbatim}
\begin{verbatim}
> currow[curcols]
V4 V5 V6 V7
"Col Parent1" NA NA NA
\end{verbatim}
\vspace{-1.5em}
\noindent\rule{0.25\textwidth}{0.4pt}
\vspace{0.5em}
\subsubsection{Case Multi-row Column Labels}
It is also quite common for Col Labels that are too wide to be
physically split over multiple rows to manage the width of the
labels. For now, we simply assume that any rows that are not full (and
hence not parents) should all really be a single row of children, and
collapse these.
\nwenddocs{}\nwbegincode{71}\sublabel{RNWTab1-Mul37-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Mul37-1}}}\moddef{Multirow Col Labels~{\nwtagstyle{}\subpageref{RNWTab1-Mul37-1}}}\endmoddef
ParePreColMultirow =
function(matData, matColLabel)\{
fullrows = apply(matColLabel, 1, function(x) all(!is.na(x)))
if(any(diff(fullrows) > 1))
warning("full rows followed by not full rows!")
if(any(fullrows))\{
pastestring = ""
pasterows = which(fullrows)
for(i in 1:length(pasterows))
pastestring[i] = paste0("matColLabel[", pasterows[i],
",,drop=FALSE]")
collapsedlabels =
eval(parse(text = paste0("paste(",
paste(pastestring, collapse = ", "), ")")))
TCRsink("MCLBefore", matColLabel)
matColLabel = rbind(matColLabel[!fullrows,,drop=FALSE],
collapsedlabels, deparse.level = 0)
TCRsink("MCLAfter", matColLabel)
\}
list(matData = matData, matColLabel = matColLabel)
\}
TTLFaliasAdd("ParePreCol", "ParePreColMultirow", "multirow",
"Base Algorithm", paste("Merge long column labels",
"that were physically split over multiple rows",
"back into a single label"))
\nwidentuses{\\{{TCRsink}{TCRsink}}\\{{TTLFaliasAdd}{TTLFaliasAdd}}}\nwindexuse{TCRsink}{TCRsink}{RNWTab1-Mul37-1}\nwindexuse{TTLFaliasAdd}{TTLFaliasAdd}{RNWTab1-Mul37-1}\nwendcode{}\nwbegindocs{72}\nwdocspar
Example values for \textbf{ToyExComplete.csv} \texttt{(ID: MCLBefore)}
\begin{verbatim}
> matColLabel
V4 V5 V6 V7 V8 V9
[1,] NA NA NA NA NA NA
[2,] "Col Parent1" NA NA NA "Col Parent2" NA
[3,] "Col" "Col" "Col" "Col" "Col" "Col"
[4,] "Child1" "Child2" "Child3" "Child4" "Child1" "Child2"
\end{verbatim}
\vspace{-1.5em}
\noindent\rule{0.25\textwidth}{0.4pt}
\vspace{0.5em}
%TCEx MCLAfter matColLabel
%TCEx MCLBefore matColLabel
Example values for \textbf{ToyExComplete.csv} \texttt{(ID: MCLAfter)}
\begin{verbatim}
> matColLabel
V4 V5 V6 V7 V8
[1,] NA NA NA NA NA
[2,] "Col Parent1" NA NA NA "Col Parent2"
[3,] "Col Child1" "Col Child2" "Col Child3" "Col Child4" "Col Child1"
V9
[1,] NA
[2,] NA
[3,] "Col Child2"
\end{verbatim}
\vspace{-1.5em}
\noindent\rule{0.25\textwidth}{0.4pt}
\vspace{0.5em}
\subsection{Parentage - Front}
\label{sec:PareFront}
This front end function takes the \verb|matLabel|, which can be the
\verb|matRowLabel| or the transpose of the \verb|matColLabel|, and
constructs an initialising \verb|plist|, which is used to make the
first call to the Main function.
\nwenddocs{}\nwbegincode{73}\sublabel{RNWTab1-Par38-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Par38-1}}}\moddef{Pare Front~{\nwtagstyle{}\subpageref{RNWTab1-Par38-1}}}\endmoddef
PareFront =
function(matLabel)
PareMain(matSub = matLabel, plist =
list(rows = 1:nrow(matLabel), cols = 1:ncol(matLabel)))
\nwindexdefn{PareFront}{PareFront}{RNWTab1-Par38-1}\eatline
\nwidentdefs{\\{{PareFront}{PareFront}}}\nwidentuses{\\{{PareMain}{PareMain}}}\nwindexuse{PareMain}{PareMain}{RNWTab1-Par38-1}\nwendcode{}\nwbegindocs{74}\nwdocspar
\subsection{Parentage - Main}
\label{sec:PareMain}
The purpose of the \verb|PareMain| function is to identify (or
\emph{Discern}, to better differentiate this stage from the
\emph{Identification} stage) hierarchical relationships (the
\emph{Parentage}) in the data.
It first makes various checks for fringe cases, then calls various
detection algorithms (\verb|Pare Low Levels|) to discern the
parentage.
\nwenddocs{}\nwbegincode{75}\sublabel{RNWTab1-Par39-1}\nwmargintag{{\nwtagstyle{}\subpageref{RNWTab1-Par39-1}}}\moddef{Pare Main~{\nwtagstyle{}\subpageref{RNWTab1-Par39-1}}}\endmoddef
PareMain =
function(matSub, plist)\{
\LA{}If only one column~{\nwtagstyle{}\subpageref{RNWTab1-Ifo40-1}}\RA{}