-
Notifications
You must be signed in to change notification settings - Fork 0
/
RJtemplate.tex
1422 lines (1270 loc) · 52.5 KB
/
RJtemplate.tex
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
% !TeX root = RJwrapper.tex
\newcommand{\sectiontidyr}{Comparing \code{namedCapture::df\_match\_variable} with \code{tidyr::extract}}
\newcommand{\sectiontrackDb}{Extract all matches from a multi-line text file via \code{str\_match\_all\_variable}}
\newcommand{\sectiontimings}{Comparing computation times of R regex packages}
\newcommand{\sectiondf}{\code{df\_match\_variable} extracts new columns from character columns in a data.frame}
\newcommand{\sectionrex}{Comparing \CRANpkg{namedCapture} variable argument syntax with \CRANpkg{rex}}
\title{Comparing \CRANpkg{namedCapture} with other R packages for
regular expressions}
\author{by Toby Dylan Hocking}
\maketitle
\abstract{Regular expressions are powerful tools for manipulating
non-tabular textual data. For many tasks (visualization, machine
learning, etc), tables of numbers must be extracted from such data
before processing by other R functions. We present the R package
\CRANpkg{namedCapture}, which facilitates such tasks by providing a new
user-friendly syntax for defining regular expressions in R code. We
begin by describing the history of regular expressions and their
usage in R. We then describe the new features of the namedCapture
package, and provide detailed comparisons with related R packages
(\CRANpkg{rex}, \CRANpkg{stringr}, \CRANpkg{stringi}, \CRANpkg{tidyr},
\CRANpkg{rematch2}, \CRANpkg{re2r}).}
\section{Introduction}
Today regular expression libraries are powerful and widespread tools
for text processing. A regular expression \dfn{pattern} is
typically a character string that defines a set of possible
\dfn{matches} in some other \dfn{subject} strings. For example
the pattern \code{o+} matches one or more lower-case o characters; it
would match the last two characters in the subject \code{foo}, and it
would not match in the subject \code{bar}.
The focus of this article is regular expressions with capture groups,
which are used to extract subject substrings. Capture groups are
typically defined using parentheses. For example, the pattern
\code{[0-9]+} matches one or more digits (e.g. \code{123} but not
\code{abc}), and the pattern \code{[0-9]+-[0-9]+} matches a range of
integers (e.g. \code{9-5}). The pattern \code{([0-9]+)-([0-9]+)} will
perform matching identically, but provides access by number/index to
the strings matched by the capturing sub-patterns enclosed in
parentheses (group 1 matches \code{9}, group 2 matches \code{5}). The
pattern \code{(?P<start>[0-9]+)-(?P<end>[0-9]+)} further provides access
by name to the captured sub-strings (\code{start} group matches
\code{9}, \code{end} group matches \code{5}). In R named capture
groups are useful in order to create more readable regular expressions
(names document the purpose of each sub-pattern), and to create more
readable R code (it is easier to understand the intent of named references than
numbered references).
We begin by providing a brief history of regular
expressions and their usage in \R. We then provide an overview of
current R packages for regular expressions.
\subsection{Origin of regular expressions and named capture groups}
Regular expressions were first proposed on paper
by \citet{Kleene56}. Among the first uses of a regular expression in
computers was for searching in a text editor \citep{Thompson68} and
lexical processing of source code \citep{Johnson68}.
A capture group in a regular expression is used to extract text that
matches a sub-pattern. In 1974, Thompson wrote the \texttt{grep}
command line program, which was among the first to support capture
groups \citep{Friedl2002}. In that program, backslash-escaped
parentheses \verb|\(\)| were used to open and close each capture
group, which could then be referenced by number (\verb|\1| for the
first capture group, etc).
The idea for named capture groups seems to have originated in 1994
with the contributions of Tracy Tims to Python 1.0.0, which used the
\verb|\(<labelname>...\)| syntax
\citep{Python-1.5.2-Misc-HISTORY}. Python 1.5 introduced the
\verb|(?P<labelname>...)| syntax for name capture groups
\citep{python-1.5-Doc-libre.tex}; the P was used to indicate that the
syntax was a Python extension to the standard.
Perl-Compatible Regular Expressions (PCRE) is a C library that is now
a widely used in free/open-source software tools such as Python and R.
PCRE introduced support for named capture in 2003, based on the Python
syntax \citep{pcre1-changelog.txt}. Starting in 2006, it supported the
\verb|(?P<labelname>...)| and \verb|(?'labelname'...)| syntax, to be
consistent with Perl and .NET \citep{pcre1-changelog.txt}.
The first regular expression support in R was provided by the TRE C
library \citep{TRE}. Although TRE supports capture groups, it does not
allow capture groups to be named. PCRE was first included in R version
1.6.0 in 2002 \citep{R.NEWS.1.txt}. The base R functions
\code{regexpr} and \code{gregexpr} can be given the \code{perl=TRUE}
argument in order to use the PCRE library, or \code{perl=FALSE} to use
the TRE C library. A major difference between the two libraries is
that TRE provides fast linear time match algorithms, whereas PCRE
is exponential time in the worst case. Although for most patterns the
time difference is negligible, malicious patterns can make PCRE run
quite a bit slower (see Section~``\sectiontimings'').
The original versions of \code{regexpr} and \code{gregexpr} only
returned the position/length of the text matched by an entire regex,
not the capture groups (even though this is supported in TRE/PCRE). I
wrote the C code that uses PCRE to extract the text matched by each
named capture group \citep{HockingBug2011}, which was accepted into R
starting with version 2.14. I presented a lightning talk at useR 2011
that showcased the new functionality \citep{HockingUseR2011}.
\subsection{Related R packages for capturing regular expressions}
\begin{table}
\centering
\begin{tabular}{llll}
Package & First match & All matches & C library \\
\hline
\pkg{base} & \code{regexpr} & \code{gregexpr} & PCRE/TRE \\
\pkg{utils} & \code{strcapture} & NA & PCRE/TRE \\
\CRANpkg{rematch2} & \code{re\_match} & \code{re\_match\_all} & PCRE/TRE\\
\CRANpkg{namedCapture} & \code{str\_match\_*}, \code{df\_match\_variable} & \code{str\_match\_all\_*} & PCRE/RE2\\
\CRANpkg{rex} & \code{re\_matches(global=FALSE)} & \code{re\_matches(global=TRUE)} & PCRE\\
\CRANpkg{stringr} & \code{str\_match} & \code{str\_match\_all} & ICU\\
\CRANpkg{stringi} & \code{stri\_match} & \code{stri\_match\_all} & ICU\\
\CRANpkg{tidyr} & \code{extract} & NA & ICU\\
\CRANpkg{re2r} & \code{re2\_match} & \code{re2\_match\_all} & RE2
\end{tabular}
\caption{R packages that provide functions for extracting first/all regex matches, and C library used.}
\label{tab:Clib}
\end{table}
\begin{table}
\centering
\begin{tabular}{llllll}
Package & subject & pattern & outputs & named & types \\
\hline
\pkg{base} & chr & chr & mat/list & yes & no \\
\code{utils::strcapture} & chr & chr & df & no & some \\
\CRANpkg{rematch2} & chr & chr & tibble & yes & no \\
\CRANpkg{namedCapture} & chr/df/dt & verbose & mat/list/df/dt & yes & any \\
\CRANpkg{rex} & chr & verbose & df/list & yes & no \\
\CRANpkg{stringr} & chr & chr & mat/list & no & no \\
\CRANpkg{stringi} & chr & chr & mat/list & no & no \\
\code{tidyr::extract} & df/dt & chr & df/dt & no & some \\
\CRANpkg{re2r} & chr & chr/compiled & df/list & yes & no
\end{tabular}
\caption{R packages provide different options for subject/pattern input, extracted text outputs, named capture groups, and type conversion.}
\label{tab:features}
\end{table}
Since the introduction of named capture support in base R version
2.14, several packages have been developed which use this
functionality, and other packages have been developed which use other
C libraries (Table~\ref{tab:Clib}). Each package supports different
options for subject/pattern input, extracted text outputs, named
capture groups, and type conversion (Table~\ref{tab:features}).
The \pkg{utils} package now includes the strcapture function, which uses the
base \code{regexec} function (also introduced in R-2.14) to extract the first
match as a data.frame with one row per subject, and one column per
capture group. It allows capture group names/types to be specified in
a prototype data.frame argument, but does not allow capture group
names in the regex pattern. PCRE is used with \code{perl=TRUE}
and TRE is used with \code{perl=FALSE}.
The \CRANpkg{rematch2} package provides the \code{re\_match} function which
extracts the first match using the base \code{regexpr} function
\citep{rematch2}. It also provides the \code{re\_match\_all} function
which extracts all matches using the base \code{gregexpr} function. In
both cases the output is a tibble (a data.frame subclass) with one row
for each subject (for all matches a list column is used). PCRE is used
with \code{perl=TRUE} and TRE is used with \code{perl=FALSE}. Although
TRE supports capture groups (and can be used via the base R \code{regexec}
function), capture groups are not supported in rematch2 with
\code{perl=FALSE} (because it uses the base \code{regexpr}/\code{gregexpr} functions
which do not return group info for TRE). Named capture groups are
supported in rematch2 with \code{perl=TRUE}.
The \CRANpkg{stringi} package provides the \code{stri\_match} and
\code{stri\_match\_all} functions, which use the ICU C library
\citep{stringi}. The \CRANpkg{stringr} package provides the \code{str\_match} and
\code{str\_match\_all} functions, which simply call the analogous
functions from \CRANpkg{stringi}. Capture groups are supported but named groups
are not, so groups must be extracted by number. The \code{stri\_match}
function returns a character matrix with one row for each subject and
one column for each capture group. The \code{stri\_match\_all} function
returns a list with one element for each subject; each element is a
data frame with one row for each match, and one column for each
capture group.
The \CRANpkg{re2r} package provides the \code{re2\_match} and
\code{re2\_match\_all} functions, which use the RE2 C++ library
\citep{re2r}. The outputs of these functions are consistent with the
\CRANpkg{stringi}/\CRANpkg{stringr} packages. The input regex pattern may be specified as
a character string or as a pre-compiled regex object (which
results in faster matching if the regex is used with several calls to
matching functions). Like TRE, the RE2 library guarantees linear
time complexity, which is useful to avoid denial-of-service attacks
from malicious patterns (see Section~``\sectiontimings'').
The \CRANpkg{rex} package provides the \code{re\_matches} function which supports
named capture groups, and always uses PCRE \citep{rex}. By default it
returns the first match (using the base \code{regexpr} function), as a
data.frame with one row for each subject, and one column for each
capture group. If the \code{global=TRUE} argument is given,
\code{gregexpr} is used to return all matches as a list of
data.frames. A unique feature of the \CRANpkg{rex} package is a set of functions
for defining a regular expression in R code, which is then converted
to a standard PCRE regex pattern string (for a detailed comparison
with the proposed syntax of the \CRANpkg{namedCapture} package, see
Section~``\sectionrex'').
The \CRANpkg{tidyr} package provides the \code{extract} function which uses the
ICU library, so does not support regex patterns with named capture
groups \citep{tidyr}. The subject is specified via the first two
arguments: (1) a data.frame, and (2) a column name. The pattern is
specified via the second two arguments: (3) a character vector for the
capture group names, and (4) the regex pattern string (it is an error
if the number of capture group names does not match the number of un-named
capture groups in the regex pattern). The pattern is used to find the
first match in each subject. The return value is a data.frame with the
same number of rows as the input, but without the subject column, and
with an additional column for each capture group.
\section{The \CRANpkg{namedCapture} package}
The \CRANpkg{namedCapture} package provides functions for extracting
numeric data tables from non-tabular text data using named capture
regular expressions. By default, \CRANpkg{namedCapture} uses the RE2 C
library if the \CRANpkg{re2r} package is available, and PCRE otherwise
(via the base \code{regexpr} and \code{gregexpr} functions). RE2 is
preferred because it is guaranteed to find a match in linear time (see
Section~\sectiontimings). However, PCRE supports some regex features
(e.g. backreferences) that RE2 does not. To tell
\CRANpkg{namedCapture} to use PCRE rather than RE2,
\code{options(namedCapture.engine="PCRE"} can be specified. For
patterns that are supported by both engines, \CRANpkg{namedCapture}
functions return the resulting match in the standard output format
described below.
The main design features of the namedCapture package are
inspired by the base R system, which provides good support for
naming objects, and referring to objects by name. In particular, the namedCapture package supports
\begin{itemize}
\item Specifying capture groups with names in a regular expression
string, and stopping with an informative error if there are un-named
capture groups.
\item Output with rownames or list names taken from the \code{name} capture group.
\item A syntax for specifying capture group names via named arguments
in R code.
\item Specifying a function for each named capture group,
which converts captured text from character to other arbitrary types.
\item Saving sub-patterns to R variables, and re-using them multiple
times in one or several patterns in order to avoid repetition.
\end{itemize}
The main functions provided by the namedCapture package are summarized
in Table~\ref{tab:functions}. We begin by introducing the \code{*\_named} functions, which take three arguments.
\begin{table}
\centering \begin{tabular}{llll}
First match & All matches & Arguments \\
\hline
\code{str\_match\_named} & \code{str\_match\_all\_named} & chr subject, chr pattern, functions \\
\code{str\_match\_variable} & \code{str\_match\_all\_variable} & chr subject, chr/list/function, ... \\
\code{df\_match\_variable} & NA & df subject, chr/list/function, ...
\end{tabular}
\caption{Functions of the
namedCapture package. The first argument of each function specifies
the subject, as either a character vector (for \texttt{str\_*})
functions, or a data.frame
(for \texttt{df\_match\_variable}). The \texttt{*\_named} functions
require three arguments, whereas the \texttt{*\_variable} functions
take a variable number of arguments.} \label{tab:functions}
\end{table}
\subsection{Three argument syntax: \code{str\_match\_named} and \code{str\_match\_all\_named}}
The most basic functions of the \CRANpkg{namedCapture} package
are \code{str\_match\_named} and \code{str\_match\_all\_named}, which accept exactly three arguments:
\begin{itemize}
\item subject: a character vector from which we want to extract
tabular data.
\item pattern: the (character scalar) regular expression with named
capture groups used for extraction.
\item fun.list: a list with names that correspond to capture groups,
and values are functions used to convert the extracted character
data to other (typically numeric) types.
\end{itemize}
For an example, we consider subjects containing genomic positions:
\begin{Schunk}
\begin{Sinput}
> chr.pos.subject <- c(
+ "chr10:213,054,000-213,055,000",
+ "chrM:111,000",
+ "this will not match",
+ NA, # neither will this.
+ "chr1:110-111 chr2:220-222") # two possible matches.
>
\end{Sinput}
\end{Schunk}
These subjects consist of a chromosome name string, a colon, a start
position, and optionally a dash and and end position. The following
pattern is used to extract those data:
\begin{Schunk}
\begin{Sinput}
> chr.pos.pattern <- paste0(
+ "(?P<chrom>chr.*?)",
+ ":",
+ "(?P<chromStart>[0-9,]+)",
+ "(?:",
+ "-",
+ "(?P<chromEnd>[0-9,]+)",
+ ")?")
>
\end{Sinput}
\end{Schunk}
The pattern above is defined using \code{paste0}, writing each named capture
group on a separate line, which increases readability of the pattern.
By default
the \code{str\_match\_named} function returns a character matrix with
one row for each subject and one column for each capture group. Column
names are taken from the group names that were specified in the
regular expression pattern:
\begin{Schunk}
\begin{Sinput}
> (match.mat <- namedCapture::str_match_named(
+ chr.pos.subject, chr.pos.pattern))
\end{Sinput}
\begin{Soutput}
chrom chromStart chromEnd
[1,] "chr10" "213,054,000" "213,055,000"
[2,] "chrM" "111,000" ""
[3,] NA NA NA
[4,] NA NA NA
[5,] "chr1" "110" "111"
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
Note that the third argument (list of conversion functions) is omitted
in the code above. In that case, the return value is a character
matrix, in which missing values indicate missing subjects or no
match. The empty string is used for optional groups which are not used
in the match (e.g. chromEnd group/column for second subject).
However we often want to extract numeric data; in this case we want to
convert chromStart/End to integers. You can do that by supplying a
named list of conversion functions as the third argument. Each
function should take exactly one argument, a character vector (data in
the matched column/group), and return a vector of the same size. The
code below specifies the \code{int.from.digits} function for both chromStart
and chromEnd:
\begin{Schunk}
\begin{Sinput}
> int.from.digits <- function(captured.text){
+ as.integer(gsub("[^0-9]", "", captured.text))
+ }
> conversion.list <- list(
+ chromStart=int.from.digits,
+ chromEnd=int.from.digits)
> (match.df <- namedCapture::str_match_named(
+ chr.pos.subject, chr.pos.pattern, conversion.list))
\end{Sinput}
\begin{Soutput}
chrom chromStart chromEnd
1 chr10 213054000 213055000
2 chrM 111000 NA
3 <NA> NA NA
4 <NA> NA NA
5 chr1 110 111
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
Note that a data.frame is returned when the third argument is
specified, in order to handle non-character data types returned by the
conversion functions.
In the examples above the last subject has two possible
matches, but only the first is returned by \code{str\_match\_named}. Use
\code{str\_match\_all\_named} to get all matches in each subject (not just the
first match).
\begin{Schunk}
\begin{Sinput}
> namedCapture::str_match_all_named(
+ chr.pos.subject, chr.pos.pattern, conversion.list)
\end{Sinput}
\begin{Soutput}
[[1]]
chrom chromStart chromEnd
1 chr10 213054000 213055000
[[2]]
chrom chromStart chromEnd
1 chrM 111000 NA
[[3]]
data frame with 0 columns and 0 rows
[[4]]
data frame with 0 columns and 0 rows
[[5]]
chrom chromStart chromEnd
1 chr1 110 111
2 chr2 220 222
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
As shown above, the result is a list with one element for
each subject. Each list element is a data.frame with one row for each
match.
\subsection{Named output for named subjects}
If the subject is named, its names will be used to name the output
(rownames or list names).
\begin{Schunk}
\begin{Sinput}
> named.subject <- c(
+ ten="chr10:213,054,000-213,055,000",
+ M="chrM:111,000",
+ two="chr1:110-111 chr2:220-222") # two possible matches.
> namedCapture::str_match_named(
+ named.subject, chr.pos.pattern, conversion.list)
\end{Sinput}
\begin{Soutput}
chrom chromStart chromEnd
ten chr10 213054000 213055000
M chrM 111000 NA
two chr1 110 111
\end{Soutput}
\begin{Sinput}
> namedCapture::str_match_all_named(
+ named.subject, chr.pos.pattern, conversion.list)
\end{Sinput}
\begin{Soutput}
$ten
chrom chromStart chromEnd
1 chr10 213054000 213055000
$M
chrom chromStart chromEnd
1 chrM 111000 NA
$two
chrom chromStart chromEnd
1 chr1 110 111
2 chr2 220 222
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
This feature makes it easy to select particular subjects/matches by
name.
\subsection{The \code{name} group specifies row names of output}
If the pattern specifies the \code{name} group, then it will be used
for the rownames of the output, and it will not be included as a
column. However if the subject has names, and the \code{name} group is
specified, then to avoid losing information the subject names are used
to name the output (and the \code{name} column is included in the
output).
\begin{Schunk}
\begin{Sinput}
> name.pattern <- paste0(
+ "(?P<name>chr.*?)",
+ ":",
+ "(?P<chromStart>[0-9,]+)",
+ "(?:",
+ "-",
+ "(?P<chromEnd>[0-9,]+)",
+ ")?")
> namedCapture::str_match_named(
+ named.subject, name.pattern, conversion.list)
\end{Sinput}
\begin{Soutput}
name chromStart chromEnd
ten chr10 213054000 213055000
M chrM 111000 NA
two chr1 110 111
\end{Soutput}
\begin{Sinput}
> namedCapture::str_match_all_named(
+ named.subject, name.pattern, conversion.list)
\end{Sinput}
\begin{Soutput}
$ten
chromStart chromEnd
chr10 213054000 213055000
$M
chromStart chromEnd
chrM 111000 NA
$two
chromStart chromEnd
chr1 110 111
chr2 220 222
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
\subsection{Readable and efficient variable argument syntax used in \code{str\_match\_variable}}
In this section we introduce the variable argument syntax used in the
\code{*\_variable} functions. This new syntax is both readable and
efficient, because it is motivated by the desire to avoid
repetitive/boilerplate code. In the previous sections we defined the
pattern using the \code{paste0} boilerplate, which is used to break the
pattern over several lines for clarity. We begin by introducing
\code{str\_match\_variable}, which extracts the first match from each
subject. Using the variable argument syntax, we can omit \code{paste0}, and
simply supply the pattern strings to \code{str\_match\_variable}
directly,
\begin{Schunk}
\begin{Sinput}
> namedCapture::str_match_variable(
+ named.subject,
+ "(?P<chrom>chr.*?)",
+ ":",
+ "(?P<chromStart>[0-9,]+)",
+ "(?:",
+ "-",
+ "(?P<chromEnd>[0-9,]+)",
+ ")?")
\end{Sinput}
\begin{Soutput}
chrom chromStart chromEnd
ten "chr10" "213,054,000" "213,055,000"
M "chrM" "111,000" ""
two "chr1" "110" "111"
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
The variable argument syntax allows further simplification by removing the named capture groups from the
strings, and adding names to the corresponding arguments. For
\code{name1="pattern1"}, namedCapture internally generates/uses the regex
\code{(?P<name1>pattern1)}.
\begin{Schunk}
\begin{Sinput}
> namedCapture::str_match_variable(
+ named.subject,
+ chrom="chr.*?",
+ ":",
+ chromStart="[0-9,]+",
+ "(?:",
+ "-",
+ chromEnd="[0-9,]+",
+ ")?")
\end{Sinput}
\begin{Soutput}
chrom chromStart chromEnd
ten "chr10" "213,054,000" "213,055,000"
M "chrM" "111,000" ""
two "chr1" "110" "111"
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
We can also provide a type conversion function on the same line as a named group:
\begin{Schunk}
\begin{Sinput}
> namedCapture::str_match_variable(
+ named.subject,
+ chrom="chr.*?",
+ ":",
+ chromStart="[0-9,]+", int.from.digits,
+ "(?:",
+ "-",
+ chromEnd="[0-9,]+", int.from.digits,
+ ")?")
\end{Sinput}
\begin{Soutput}
chrom chromStart chromEnd
ten chr10 213054000 213055000
M chrM 111000 NA
two chr1 110 111
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
Note the repetition in the chromStart/End lines --- the same pattern
and type conversion function is used for each group. This repetition
can be avoided by creating and using a sub-pattern list variable,
\begin{Schunk}
\begin{Sinput}
> int.pattern <- list("[0-9,]+", int.from.digits)
> namedCapture::str_match_variable(
+ named.subject,
+ chrom="chr.*?",
+ ":",
+ chromStart=int.pattern,
+ "(?:",
+ "-",
+ chromEnd=int.pattern,
+ ")?")
\end{Sinput}
\begin{Soutput}
chrom chromStart chromEnd
ten chr10 213054000 213055000
M chrM 111000 NA
two chr1 110 111
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
Finally, the non-capturing group can be replaced by an un-named list:
\begin{Schunk}
\begin{Sinput}
> namedCapture::str_match_variable(
+ named.subject,
+ chrom="chr.*?",
+ ":",
+ chromStart=int.pattern,
+ list(
+ "-",
+ chromEnd=int.pattern
+ ), "?")
\end{Sinput}
\begin{Soutput}
chrom chromStart chromEnd
ten chr10 213054000 213055000
M chrM 111000 NA
two chr1 110 111
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
In summary, the \code{str\_match\_variable} function takes a variable number of arguments, and allows for a shorter, less repetitive, and thus more user-friendly syntax:
\begin{itemize}
\item The first argument is the subject character vector.
\item The other arguments specify the pattern, via character strings,
functions, and/or lists.
\item If a pattern (character/list) is named, we use the argument name in R for the capture
group name in the regex.
\item Each function is used to convert the text extracted by the previous
named pattern argument. (type conversion can only be used with named R arguments, NOT with explicitly specified named groups in regex strings)
\item R sub-pattern variables
may be used to avoid repetition in the definition of the pattern and type conversion functions.
\item Each list generates a group in the regex (named list = named capture group, un-named list = non-capturing group).
\item All patterns are pasted together in the order that they appear in
the argument list.
\end{itemize}
\subsection{\sectiontrackDb}
\label{sec:trackDb}
The variable argument syntax can also be used with
\code{str\_match\_all\_variable}, which is for the common case of extracting
each match from a multi-line text file. In this section we demonstrate
how to use \code{str\_match\_all\_variable} to extract data.frames from a
non-tabular text file.
\begin{Schunk}
\begin{Sinput}
> trackDb.txt.gz <- system.file(
+ "extdata", "trackDb.txt.gz", package="namedCapture")
> trackDb.lines <- readLines(trackDb.txt.gz)
>
\end{Sinput}
\end{Schunk}
Some representative lines from that file are shown below.
\begin{Schunk}
\begin{Sinput}
> cat(trackDb.lines[78:107], sep="\n")
\end{Sinput}
\begin{Soutput}
track peaks_summary
type bigBed 5
shortLabel _model_peaks_summary
longLabel Regions with a peak in at least one sample
visibility pack
itemRgb off
spectrum on
bigDataUrl http://hubs.hpc.mcgill.ca/~thocking/PeakSegFPOP-/peaks_summary.bigBed
track bcell_McGill0091
parent bcell
container multiWig
type bigWig
shortLabel bcell_McGill0091
longLabel bcell | McGill0091
graphType points
aggregate transparentOverlay
showSubtrackColorOnUi on
maxHeightPixels 25:12:8
visibility full
autoScale on
track bcell_McGill0091Coverage
bigDataUrl http://hubs.hpc.mcgill.ca/~thocking/PeakSegFPOP-/samples/bcell/McGill0091/coverage.bigWig
shortLabel bcell_McGill0091Coverage
longLabel bcell | McGill0091 | Coverage
parent bcell_McGill0091
type bigWig
color 141,211,199
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
Each block of text begins with \code{track} and includes several lines of
data before the block ends with two consecutive newlines. That pattern
is coded below:
\begin{Schunk}
\begin{Sinput}
> fields.mat <- namedCapture::str_match_all_variable(
+ trackDb.lines,
+ "track ",
+ name="\\S+",
+ fields="(?:\n[^\n]+)*",
+ "\n")
> head(substr(fields.mat, 1, 50))
\end{Sinput}
\begin{Soutput}
fields
bcell "\nsuperTrack on show\nshortLabel bcell\nlongLabel bce"
kidneyCancer "\nsuperTrack on show\nshortLabel kidneyCancer\nlongLa"
kidney "\nsuperTrack on show\nshortLabel kidney\nlongLabel ki"
leukemiaCD19CD10BCells "\nsuperTrack on show\nshortLabel leukemiaCD19CD10BCe"
monocyte "\nsuperTrack on show\nshortLabel monocyte\nlongLabel "
skeletalMuscleCtrl "\nsuperTrack on show\nshortLabel skeletalMuscleCtrl\n"
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
Note that this function assumes that its subject is a character vector
with one element for each line in a file. The elements are pasted
together using newline as a separator, and the regex is used to find
all matches in the resulting multi-line string. The code above creates
a data frame with one row for each track block, with rownames given by
the track line (because of the capture group named name), and one
fields column which is a string with the rest of the data in that
block.
Each block has a variable number of lines/fields. Each line starts
with a field name, followed by a space, followed by the field
value. That regex is coded below:
\begin{Schunk}
\begin{Sinput}
> fields.list <- namedCapture::str_match_all_named(
+ fields.mat[, "fields"], paste0(
+ "\\s+",
+ "(?P<name>.*?)",
+ " ",
+ "(?P<value>[^\n]+)"))
> fields.list$bcell_McGill0091Coverage
\end{Sinput}
\begin{Soutput}
value
bigDataUrl "http://hubs.hpc.mcgill.ca/~thocking/PeakSegFPOP-/samples/bcell/McGill0091/coverage.bigWig"
shortLabel "bcell_McGill0091Coverage"
longLabel "bcell | McGill0091 | Coverage"
parent "bcell_McGill0091"
type "bigWig"
color "141,211,199"
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
The result is a list of data frames.
There is a list element for each block, named by track. Each list
element is a data frame with one row per field defined in that
block (rownames are field names). The names/rownames make it easy
to write R code that selects individual elements by name.
In the example above we extracted all fields from all tracks (using
two regexes, one for the track, one for the field). In the example
below we use a single regex to extract the name of each track, and split
components into separate columns. It also demonstrates how to use nested named
capture groups, via a named list which contains other named patterns.
\begin{Schunk}
\begin{Sinput}
> match.df <- namedCapture::str_match_all_variable(
+ trackDb.lines,
+ "track ",
+ name=list(
+ cellType=".*?",
+ "_",
+ sampleName=list(
+ "McGill",
+ sampleID=int.pattern),
+ dataType="Coverage|Peaks",
+ "|",
+ "[^\n]+"))
> match.df["bcell_McGill0091Coverage", ]
\end{Sinput}
\begin{Soutput}
cellType sampleName sampleID dataType
bcell_McGill0091Coverage bcell McGill0091 91 Coverage
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
Exercise for the reader: modify the above in order to capture the
bigDataUrl field, and three additional columns (red, green, blue) from
the color field.
\subsection{\sectiondf}
\label{sec:df_match_variable}
We also provide \code{namedCapture::df\_match\_variable} which extracts text
from several columns of a data.frame, using a different named capture
regular expression for each column.
\begin{itemize}
\item It requires a data.frame as the first argument.
\item It takes a variable number of other arguments, all of which must be
named. For each other argument we call \code{str\_match\_variable} on one
column of the input data.frame.
\item Each argument name specifies a column of the data.frame which will
be used as the subject in \code{str\_match\_variable}.
\item Each argument value specifies a pattern, in
list/character/function variable argument syntax.
\item The return value is a data.frame with the same number of rows as the
input, but with an additional column for each named capture
group. New columns are named using the convention
\code{subjectColumnName.groupName}.
\end{itemize}
This function can greatly simplify the code required to create numeric
data columns from character data columns. For example consider the
following data which was output from the SLURM sacct command line program.
\begin{Schunk}
\begin{Sinput}
> (sacct.df <- data.frame(
+ Elapsed=c("07:04:42", "07:04:42", "07:04:49", "00:00:00", "00:00:00"),
+ JobID=c("13937810_25", "13937810_25.batch", "13937810_25.extern",
+ "14022192_[1-3]", "14022204_[4]"), stringsAsFactors=FALSE))
\end{Sinput}
\begin{Soutput}
Elapsed JobID
1 07:04:42 13937810_25
2 07:04:42 13937810_25.batch
3 07:04:49 13937810_25.extern
4 00:00:00 14022192_[1-3]
5 00:00:00 14022204_[4]
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
Say we want to filter by the total Elapsed time (which is reported as
hours:minutes:seconds), and base job id (which is the number before
the underscore in the JobID column). We begin by defining a pattern
that matches a range of integer task IDs in square brackets, and applying that
pattern to the JobID column:
\begin{Schunk}
\begin{Sinput}
> range.pattern <- list(
+ "[[]",
+ task1=int.pattern,
+ list(
+ "-",
+ taskN=int.pattern
+ ), "?",
+ "[]]")
> namedCapture::df_match_variable(sacct.df, JobID=range.pattern)
\end{Sinput}
\begin{Soutput}
Elapsed JobID JobID.task1 JobID.taskN
1 07:04:42 13937810_25 NA NA
2 07:04:42 13937810_25.batch NA NA
3 07:04:49 13937810_25.extern NA NA
4 00:00:00 14022192_[1-3] 1 3
5 00:00:00 14022204_[4] 4 NA
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
The result shown above is another data frame with an additional column for each
named capture group.
Next, we define another pattern that matches either one task ID
or the previously defined range pattern:
\begin{Schunk}
\begin{Sinput}
> task.pattern <- list(
+ "_", list(
+ task=int.pattern,
+ "|",#either one task(above) or range(below)
+ range.pattern))
> namedCapture::df_match_variable(sacct.df, JobID=task.pattern)
\end{Sinput}
\begin{Soutput}
Elapsed JobID JobID.task JobID.task1 JobID.taskN
1 07:04:42 13937810_25 25 NA NA
2 07:04:42 13937810_25.batch 25 NA NA
3 07:04:49 13937810_25.extern 25 NA NA
4 00:00:00 14022192_[1-3] NA 1 3
5 00:00:00 14022204_[4] NA 4 NA
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
Finally, we use the previously defined patterns to match the complete JobID
column, along with the Elapsed column:
\begin{Schunk}
\begin{Sinput}
> namedCapture::df_match_variable(
+ sacct.df,
+ JobID=list(
+ job=int.pattern,
+ task.pattern,
+ list(
+ "[.]",
+ type=".*"
+ ), "?"),
+ Elapsed=list(
+ hours=int.pattern,
+ ":",
+ minutes=int.pattern,
+ ":",
+ seconds=int.pattern))
\end{Sinput}
\begin{Soutput}
Elapsed JobID JobID.job JobID.task JobID.task1 JobID.taskN
1 07:04:42 13937810_25 13937810 25 NA NA
2 07:04:42 13937810_25.batch 13937810 25 NA NA
3 07:04:49 13937810_25.extern 13937810 25 NA NA
4 00:00:00 14022192_[1-3] 14022192 NA 1 3
5 00:00:00 14022204_[4] 14022204 NA 4 NA
JobID.type Elapsed.hours Elapsed.minutes Elapsed.seconds
1 7 4 42
2 batch 7 4 42
3 extern 7 4 49
4 0 0 0
5 0 0 0
\end{Soutput}
\begin{Sinput}
>
\end{Sinput}
\end{Schunk}
The code above specifies two named arguments to
\code{df\_match\_variable}. Each named argument specifies a column from