---
title: "Ling 120, session 02: R basics 2"
author:
   - name: "[Stefan Th. Gries](https://www.stgries.info)"
     affiliation:
        - UC Santa Barbara
        - JLU Giessen
     orcid: 0000-0002-6497-3958
date: "2027-01-12 12:34:56"
date-format: "DD MMM YYYY HH-mm-ss"
editor: source
format:
   html:
      page-layout: full
      code-fold: false
      code-link: true
      code-copy: true
      code-tools: true
      code-line-numbers: true
      code-overflow: wrap
      number-sections: true
      smooth-scroll: true
      toc: true
      toc-depth: 4
      number-depth: 4
      toc-location: left
      mainfont: Times New Roman
      monofont: Lucida Console
      tbl-cap-location: top
      fig-cap-location: bottom
      fig-width: 6
      fig-height: 6
      fig-format: png
      fig-dpi: 300
      fig-align: center
      embed-resources: true
      include-in-header:
         text: '<link rel="shortcut icon" href="https://www.stgries.info/favicon.ico" type="image/x-icon" />'
execute:
   cache: false
   echo: true
   eval: true
   warning: false
---

# Text processing 1

We first clear memory and load `magrittr`:

```{r prepworkspace}
rm(list=ls(all=TRUE)); library(magrittr)
```

## Various text processing functions

The function `noquote` prints character **strings without quotes**:

```{r noquote}
# works on single-element character strings:
(x1 <- "know")
noquote(x1)

# works on multi-element character strings:
(x2 <- c("We", "do", "not", "know"))
noquote(x2)
```

The function `nchar` returns the **number(s) of characters** of the element(s) of a character vector:

```{r nchar}
nchar(x1)
nchar(x2)
```

The function `substr` returns (a) **substring(s)** of the (elements of a) character vector:

```{r substr}
# works on single-element character strings:
substr(
   x=x1,
   start=1,
   stop=2)

# works on multi-element character strings:
substr(
   x=x2,
   start=1,
   stop=2)
```

Note: this can be useful together with `nchar`: How do we check whether elements of this character vector `qwe` end in "ly"? Like this:

```{r substrfinally}
(qwe <- c("Interestingly", "Holy", "Pfote"))
#| code-fold: true
substr(
   qwe,
   nchar(qwe)-1,
   nchar(qwe))=="ly"
```

But actually, at some point, the R Core Team added functions `startsWith` and `endsWith`, the latter of which would be useful here:

```{r}
qwe[endsWith(qwe, "ly")]
```

You can change elements of character vectors to **upper or lower case** with `tolower` and `toupper` respectively:

```{r toXer}
tolower(qwe)
toupper(qwe)
```

You can **replace complete sets of characters** in character strings by another set, very useful for transliteration:

```{r chartr}
(qwe <- "Commander Sheridan was assigned as ambassador to Minbar")
chartr(
   old="aeiou",
   new="VVVVV",
   x=qwe)
```

You can delete leading and/or trailing whitespace with `trimws`:

```{r trimws}
trimws(c("   a b c  d e f  ", " a   b   c    "))
```

## Merging strings

You can **merge character strings** with the function `paste`, which takes two main arguments (after the things to be merged of course):

* `collapse`: when `paste` conflates everything into a single string, what's between the parts that are collapsed into one string;
* `sep`: what `paste` puts between the character strings.

The most frequent scenario is probably one where you give `paste` a multi-element vector and use something like `collapse=""` to merge all elements into a one-element vector:

```{r pastecoll}
(multi_element_vector <- c(
   "The Fulton County Grand Jury said Friday an investigation",
   "of Atlanta's recent primary election produced \"no evidence\" that",
   "any irregularities took place.   The jury further said in term-end",
   "presentments that the City Executive Committee, which had over-all",
   "charge of the election, \"deserves the praise and thanks of the frog"))
paste(
   multi_element_vector,
   collapse=" ")
```

The second-most frequent scenario is probably the one where you give `paste` two equally long multi-element vectors to paste them together in a pairwise fashion:

```{r pastesep}
(multi_element_vector_words <- c("I", "do", "not", "know"))
(multi_element_vector_tags <- c("PNP", "VDB", "NEG", "VVB"))
(tagged_corpus <- paste(
   multi_element_vector_words,
   multi_element_vector_tags,
   sep="_"))
```

# Data structures 2: lists

While the vector is probably the most central data structure for text processing in R, it is necessary to also briefly talk about lists. Lists are a versatile data structure, which can in turn contain various different data structures within them. For example, a list can contain different kinds of vectors, data frames, and other lists, as well as other data structures:

```{r createlist1}
some_vect <- c(1:10)                           # define a few
some_dafr <- data.frame(X=1:3, Y=letters[1:3]) # 'things' to put
some_fact <- factor(letters[1:10])             # into a list
(a_list <- list(some_vect, some_dafr, some_fact)) # create a list
```

As you can see, the three different elements -- a vector of numbers, a data frame, and a factor -- are now stored in a single data structure:

```{r strOFlist}
str(a_list)
```

This kind of data structure is interesting because it can contain many different things and because we can access individual parts of it in ways similar to those we use for other data structures. As the above output indicates, the elements in lists are numbered and the numbers are put between **double square brackets**. Thus, we can access each element of the list like this:

```{r listsubset1}
#| collapse: true
a_list[[1]] # the 1st element of a list as a numeric vector
a_list[[2]] # the 2nd element of a list as a data frame
a_list[[3]] # the 3rd element of a list as a factor
```

It is important to bear in mind that there are two ways of accessing a list's elements with subsetting. The one with double square brackets is the one suggested by how a list is shown in the console. This way, we get each element as the kind of data structure we entered it into the list, namely as a vector, a data frame, and a factor respectively. What, however, happens when we use the general subsetting approach, which you know uses single square brackets?

```{r listsubset2}
#| collapse: true
a_list[[1]] # the 1st element of a list as a ...?
a_list[1]   # the 1st element of a list as a ...?
```

The difference is this: If we access a component of a list with *double* square brackets, we get that component as an instance of the kind of data structure as it was entered into the list (see the first output, which is a regular numeric vector). If we access a component of a list with *single* square brackets, we get that component as an instance of the data structure from which we're plucking it, i.e., here as a list.

An alternative approach is to make sure the list components have names. We can do that just like we would with vectors when the list has already been created like above:

```{r listsubsetnames}
#| collapse: true
names(a_list) <- c("Part1", "Part2", "Part3") # give the list parts names
str(a_list) # check out the list's structure
```

Or, you can actually do that already while you are creating the list:

```{r createlist2}
a_list <- list( # make a_list a list w/
   "Part1"=some_vect, # this as the 1st component (w/ that name)
   "Part2"=some_dafr, # this as the 2nd component (w/ that name)
   "Part3"=some_fact) # this as the 3rd component (w/ that name)
str(a_list) # check out its structure
```

Either way, once the list components have names, we can use by now familiar ways of subsetting as well for both accessing list parts ...

```{r listsubset3}
#| eval: false
a_list[[1]]       # all these three
a_list[["Part1"]] # return the same:
a_list$Part1      # a numeric vector
```

... or putting something into a (new) list part:

```{r newlistpart}
a_list[[4]] <- c("abstemiously", "facetiously")
a_list
```

And of course the same logic works for accessing parts of parts of lists:

```{r listsubsetsubset}
#| collapse: true
a_list[[1]][5:7]
a_list[["Part1"]][5:7]
a_list$Part1[5:7]
```

# Text processing 2
## Splitting up strings

Remember that, before we talked about lists, we discussed `paste` using this example where we gave `paste` two equally long multi-element vectors to paste them together in a pairwise fashion:

```{r pastesetpagain}
(multi_element_vector.words <- c("I", "do", "not", "know"))
(multi_element_vector.tags <- c("PNP", "VDB", "NEG", "VVB"))
(tagged_corpus <- paste(
   multi_element_vector.words,
   multi_element_vector.tags,
   sep="_"))
```

You can of course also do the opposite, namely **split up character strings** and you do so with the function `strsplit`, which -- for now! -- takes two main arguments:

* `x`: the character vector (whose elements) you want to split up;
* `split`: the characters to use for splitting, which means those will be 'lost':

```{r strsplit}
strsplit(
   x=tagged_corpus,
   split="_")
```

Its output is a list -- that's why we talked about lists in the meantime -- of length `length(x)`, each element of which contains a character vector with the result of splitting each element of `x` (which is useful because it preserves the context of the now split-up parts).

The following are two very frequent next steps. First, you may not want context (e.g. in a frequency list context). In that case, you can just `unlist` because then you have a vector you could easily tabulate etc.:

```{r strsplitANDunlist}
(words <- unlist(
   strsplit(
      multi_element_vector,
      " "
)))
sort(table(tolower(words))) # or
# words %>% tolower %>% table %>% sort
```

Second, you may want to extract all elements in a certain position in each list element. For instance, if `tagged_corpus` is what you have, this is how you get the words and the tags in separate vectors:

```{r strsplitANDextract}
(tagged_corpus)
(tagged_corpus.split <- strsplit(
   x=tagged_corpus,
   split="_"))

(words <- sapply(       # make words the result of applying
   tagged_corpus.split, # to the list tagged_corpus.split
   "[",                 # the subsetting/extraction function
   1))                  # namely always extract element 1
(tags <- sapply(        # make tags the result of applying
   tagged_corpus.split, # to the list tagged_corpus.split
   "[",                 # the subsetting/extraction function
   2))                  # namely always extract element 2
```

Note what `sapply` does with the `1` and the `2` here ... This is something you may not be used to from other programming languages.

:::{.callout-tip collapse="true"}
Check out the function `tapply` as well, it's extremely useful and we'll need it in session 03 and others ...
:::

Another useful application is to make `split` be an empty character string, then `strsplit` splits up character by character:

```{r strsplitINempty}
table(unlist(strsplit(
   x=tagged_corpus,
   split="")))
```

### Exercises 1

Use R functions to

* determine which characters occur how often in tagged_corpus

```{r exercises1_1}
(qwe <- tagged_corpus %>% strsplit("") %>% unlist %>% table)
```

* determine which character is used most often -- is that a letter?

```{r exercises1_2}
qwe[which(qwe==max(qwe))] %>% names
```

* determine whether this results changes if you do this case-insensitively

```{r exercises1_3}
(asd <- tagged_corpus %>% tolower %>% strsplit("") %>% unlist %>% table)
asd[which(asd==max(asd))] %>% names
```

* determine which of the words (just the words) is longest

```{r exercises1_4}
(zxc <- sapply(tagged_corpus.split, "[", 1))
(zxc <- setNames(nchar(zxc), zxc))
zxc[which(zxc==max(zxc))] %>% names
```

## Searching within strings

There are essentially two or three main workhorse functions to search for strings within base R. Let's check it out with out with our vector `multi_element_vector`:

```{r remind}
multi_element_vector
```

### The function `grep`

The function `grep` minimally requires two arguments:

* `pattern`: what to look for;
* `x`: in what character vector to look for it.

In that case its result is the position indices of the elements of `x` in which `pattern` is found one or more times (!):

```{r grepsimplest}
grep(
   pattern="said",
   x=multi_element_vector)
```

But often we want the matches, not just the position, which we can get in three ways: one is a bit clumsy, one was the default for years, and the last one is the new, best way:

```{r grepvalue}
# clumsy: we use those numbers to subset
multi_element_vector[grep("said", multi_element_vector)]
# better: use value=TRUE
grep(
   pattern="said",
   x=multi_element_vector,
   value=TRUE)
# best: use the new function grepv
grepv(
   pattern="said",
   x=multi_element_vector)
```

You can also get the opposite: all the elements of `x` that do *not* contain `pattern`, and you can again do so in the three ways just discussed:

```{r grepinvert}
# clumsy: use set-theoretic functions such as setdiff
multi_element_vector[setdiff(seq(multi_element_vector), grep("said", multi_element_vector))]
# better: use invert=TRUE
grep(
   pattern="said",
   x=multi_element_vector,
   invert=TRUE,
   value=TRUE)
# best: use invert=TRUE but with grepv
grepv(
   pattern="said",
   x=multi_element_vector,
   invert=TRUE)
```

Finally, you can use the argument `ignore.case` (default=`FALSE`) to do case-insensitive searches:

```{r grepigncase}
grep(
   pattern="SAID",
   x=multi_element_vector,
   ignore.case=TRUE,
   value=TRUE)
```

The function `grepl` is a bit different: it returns a logical vector as long as `length(x)` indicating for each element of `x` whether it contained `pattern` one or more times (!):

```{r grepl}
grepl(
   pattern="said",
   x=multi_element_vector)
```

### The function `gregexpr`

Since you can see we always get the complete match, which often we do *not* want, the other useful function is `gregexpr`: it's output is voluminous and we won't discuss all of it so I am showing its structure here, not its raw form:

```{r gregexpr}
str(ge.result <-
   gregexpr(
      pattern="the",
      text=multi_element_vector))
```

Like with `strsplit`, its output is a list of length `length(text)`, each element of which is a numeric vector

* stating where in the relevant element of `text` the match(es) found **begin**; or
* if the element is -1, stating that there was no match.

Look:

```{r gregexprpos}
sapply(X=ge.result, FUN=as.numeric)
```

This means

* elements 1 and 2 of `multi_element_vector` do not contain "the";
* element 3 of `multi_element_vector` contains 1 "the", it begins at character position 46;
* element 4 of `multi_element_vector` contains 1 "the", it begins at character position 19;
* element 5 of `multi_element_vector` contains 3 "the", they begin at character positions 11, 35, 60.

Each of these numeric vectors also has an attribute `match.length`, which says **how long the match is** -- here of course all are 3, because we looked for a fixed "the":

```{r gregexprlen}
sapply(X=ge.result, FUN=attr, "match.length")
```

Thus, if you want to torture yourself, you can get these matches like this:

```{r gregexprnightmare}
# extract substrings from
substr(
   rep(                     # the repeated elements
      multi_element_vector, # of the input (corpus) vector,
      # where the repetitions are as often as the elements have matches:
      sapply(ge.result, # apply to each element of gregexpr's output list
             length)),  # the function length (to count how many matches there are
   # where the substring extractions have these starting positions
   unlist(ge.result),
   # and end positions of the starting positions plus
   unlist(ge.result) + unlist(sapply(ge.result, attr, "match.length"))-1
) # end of substr
```

Maybe, just maybe, this is better:

```{r regmatches}
regmatches(                # extract matches
   x=multi_element_vector, # from the input character vector,
   m=ge.result)            # namely those defined in this (gregexpr) result
```

### The functions `just.matches` and `exact.matches.2`

Instead of always using `gregexpr` and `regmatches` together (and the corpus that is searched twice), one should make this easier by writing a small function like `just.matches`:

```{r justmatchesvec}
just.matches <- function (search.expr, corpus.v, perl=TRUE, vectorize=TRUE, ...) {
   output <- regmatches(corpus.v, gregexpr(search.expr, corpus.v, perl=perl, ...))
   if (vectorize) { output <- unlist(output) }; return(output)
}
just.matches("the", multi_element_vector)
```

And if you need the context, you set the argument `vectorize` to `FALSE`:

```{rjustmatcheslist}
just.matches("the", multi_element_vector, vectorize=FALSE)
```

The book actually discusses and provides a function `exact.matches.2`, which can provide the exact matches as well as concordance displays. You download that function from my website into R with the `source` function and then you can use it:

```{r em2}
source("https://www.stgries.info/exact.matches.2.r")
exact.matches.2("the", multi_element_vector)[[1]] # same as just.matches
cat(exact.matches.2("the", multi_element_vector)[[4]], sep="\n") # concordance
```

Note also that R offers a function `gregexec`, which can be useful if you have multiple captured groups to recover from strings; this is something you might want to look at after session 3 or 4 when you have more experience with captured groups. 

## Replacing within strings

The main replacement function is `gsub`. Its most basic use is pretty self-explanatory and looks like this:

```{r gsub1}
gsub(
   pattern="said",
   replacement="***SAID***",
   x=multi_element_vector)
```

Note that while the search expression `pattern` can be searched for case-insensitively (with `ignore.case=TRUE`), (so far) the replacement will be fixed to whatever you made it:

```{r gsub2}
gsub(
   pattern="the",
   replacement="***THE***",
   x=multi_element_vector,
   ignore.case=TRUE)
```

# Text processing 3: regular expressions 1

Just about all text processing operations so far were concerned with literal searches: apart from case sensitivity, we didn't/couldn't do much else. This will now change as we begin to tackle [regular expressions](https://www.regular-expressions.info/index.html). In order to use the whole range of regexes, **we will now always add an argument `perl=TRUE`** to the uses of the functions `grep`/`grepl`, `gregexpr`, `gsub`, and `strsplit`.

## Anchors

Anchors are regexes that tie a match to a certain position in the string. These are especially useful:

* `^` means 'the following stuff needs to be at the beginning of the string;
* `$` means 'the preceding stuff needs to be at the end of the string:

```{r playWITHqwe}
(qwe <- c("their", "other", "filth", "go-rp."))
grep("th", # find "th"
     qwe,   # in qwe
     perl=TRUE, value=TRUE)
grep("^th", # find "th" in qwe but only at the beginning of a string
     qwe,   # in qwe
     perl=TRUE, value=TRUE)
grep("th$", # find "th" in qwe but only at the end of a string
     qwe,   # in qwe
     perl=TRUE, value=TRUE)
```

Note that this means that

* the `^` in the regex doesn't really 'correspond to' or **consume a character**, whereas
* the `t` and the `h` in the regex do 'correspond to' or **consume a character**.

## Regexes consuming characters
### Anything

The period matches 'any character but a new line'.

```{r anything}
qwe # to remind you what qwe was
gsub(".", "_", qwe, perl=TRUE)
```

What if you want to really only find a period? You need to tell R 'this time, I really mean a period so don't interpret the period as a regex!'. You do that with a so-called **escape character**, a backslash, which needs to be doubled here:

```{r realdot}
qwe # to remind you what qwe was
gsub("\\.", "_", qwe, perl=TRUE)
```

#### Exercises 2

Here's a vector `txt` to play with (use this [regexr page](https://regexr.com) or [this one](https://regex101.com) if you think it helps (it usually does ...)):

```{r exercises2_createtxt}
(txt <- c("This is a first example sentence.", "And this is a second example sentence."))
```

* Find the element of the vector `txt` that starts with a "T".

```{r exercises2_1}
grep("^T", txt, perl=TRUE, value=TRUE)
```

* Change string-final periods in `txt` into exclamation marks.

```{r exercises2_2}
gsub("\\.$", "!", txt, perl=TRUE)
```

* Split up the vector `txt` into words using the tags:

```{r exercises2_3}
txt <- "<w DPS>my <w NN1>mum <w CJC>and <w DPS>my <w NN1>aunt <w VVD>went <w PRP>into <w NN1>service"
unlist(           # vectorize
   strsplit(      # the list returned when you split
      txt,        # txt
      "<w ...>",  # at every occurrence of <w ...>
      perl=TRUE)) # using Perl-compatible regular expressions
# this (in pipe notation) would then also take care of the spaces:
txt %>% strsplit("<w ...>", perl=TRUE) %>% unlist %>% trimws
```

### Single-character alternatives (character classes)

If you want to find one of several single-character alternatives, you can define a so-called **character class** by listing those single-character alternatives between square brackets:

```{r charclass}
qwe # to remind you what qwe was
gsub("[aeiou]", "_", qwe, perl=TRUE)
```

Since these are single-character alternatives, their order doesn't matter: `[aeiou]` is the same as `[ueaio]`. If you want the opposite of a character class, use a caret `^` as the first character in the character class:

```{r charclassnot}
qwe # to remind you what qwe was
gsub("[^aeiou]", "_", qwe, perl=TRUE)
```

Thus, the meaning of `^` depends on its context: 'beginning of string' if it's at the beginning of a string but 'not' if it's at the beginning of a character class!

You can also specify character ranges:

* this would find any one of the letters from "a" to "z": `[a-z]`; thus, the hyphen/minus is not interpreted as a single-character alternative now, now it's a range operator;
* this would find any one of the digits: `[0-9]`.

That means if you want to include a hyphen/minus in your character class, put it at the front so R knows it's not a range operator (because no starting point of the range is provided before it):

```{r charclasshyph}
qwe # to remind you what qwe was
gsub("[-t]", "_", qwe, perl=TRUE)
```

R has some predefined character classes that can be useful. The following ones consume characters, meaning they would be found and replaced when used with `gsub`:

* `\\d` any one digit, where digit is defined as `[0-9]`, and `\\D` is its opposite;
* `\\w` any one word character, where word character is defined as `[0-9a-ZA-Z_]`, and `\\W` is its opposite;
* `\\s` is a whitespace character, i.e. a space, a tab stop, or a newline (both `\n` and `\r`);

Here are some examples:

```{r charclasspredef}
gsub("\\d", "_", "a1 > b2 < c3\n", perl=TRUE)
gsub("\\w", "_", "a1 > b2 < c3\n", perl=TRUE)
gsub("\\s", "_", "a1 > b2 < c3\n", perl=TRUE)
```

Another useful predefined character class is that of a word boundary, which does not consume a character (and is therefore a bit like an anchor). A word boundary is the position between a word character and a non-word character (as defined above and in either order), meaning it's

* the *position between* `\\w\\W`, or
* the *position between* `\\W\\w`.

Here are some examples:

```{r wordboundary}
gsub("\\br", "_", "The Minbari retreated from the Shadow fighter.", perl=TRUE)
gsub("r\\b", "_", "The Minbari retreated from the Shadow fighter.", perl=TRUE)
```

### Multiple-character alternatives

If you want to find one of several multi-character alternatives, you can list those between parentheses `()` and separate them with pipes `|`:

```{r multicharaltern}
gsub("(re|er)", "__", "The Minbari retreated from the Shadow fighter.", perl=TRUE)
```

(That means, you *could* write `[aeiou]` as `(a|e|i|o|u)`, but why would you want to ...) Note: the **'parenthesization' makes the parenthesized characters a unit**.

#### Exercises 3

Remember the vector `txt`? (Use this [regexr page](https://regexr.com) or [this one](https://regex101.com) if you think it helps (it usually does ...))

```{r reminderOFtxt}
(txt <- c("This is a first example sentence.", "And this is a second example sentence."))
```

* In the vector `txt`, replace "a first" and "a second" by "another".

```{r exercises3_1}
gsub("a (first|second)", "another", txt, ignore.case=TRUE, perl=TRUE)
```

* Write a regex that finds both the British and American spelling(s) of "analyze" in the vector `c("analyze", "analyse")`.

```{r exercises3_2}
grep("analy[sz]e", c("analyze", "analyse"), perl=TRUE, value=TRUE)
```

* Write a regex that finds both the British and American spelling of "color" in the vector `c("color", "colour")`.

```{r exercises3_3}
grep("colou?r", c("color", "colour"), perl=TRUE, value=TRUE)
```

* Write a regex that finds all likely (mis)spellings of separate in the vector `c("separate", "seperate", "separete")`.

```{r exercises3_4}
grep("sep[ae]r[ae]te", c("separate", "seperate"), perl=TRUE, value=TRUE)
```

* Split up the vector `txt` into words and punctuation marks using the tags:

```{r exercises3_5}
txt <- "<w DPS>my <w NN1>mum<c PUN>, <w DPS>my <w NN1>aunt <w VVD>went <w PRP>into <w NN1>service"
unlist(             # vectorize
   strsplit(        # the list returned when you split
      txt,          # txt
      "<[wc] ...>", # at every occurrence of <[wc] ...>
      perl=TRUE))   # using Perl-compatible regular expressions
```

More advanced: write a small script that

* unzips the file <_inputfiles/coha_sample.zip>;
* loops over the files in there such that
   + you load each file (you must use the additional argument `skipNul=TRUE`) and discard its first line;
   + you use some regex (I suggest `gsub`) to just retain the words (which are in the 1st column of a tab-delimited file);
   + you save them in a vector `collector` that grows over the loop (bad practice!);
* deletes the unzipped files;
* shows the 30 most frequent words.

```{r exercises3_6}
unzip("_inputfiles/coha_sample.zip", # unzip this zip archive
      exdir="_inputfiles")           # into the _inputfiles folder/directory
corpus_files <- dir(          # make corpus_files the content of the directory
   "_inputfiles/coha_sample", # <_inputfiles/coha_sample>
    recursive=TRUE,           # browse all sub-folders
    full.names=TRUE)          # keep full path information
collector <- character() # create collector
for (i in seq(corpus_files)) { # for each file
   current_corpus_file <-   # make current_corpus_file the result of
      scan(corpus_files[i], # loading the i-th corpus file
        what=character(),   # which contains text, not numbers
        sep="\n",           # elements are separated by line breaks
        quote="",           # there are no quotes in there
        comment.char="",    # and no comment characters
        skipNul=TRUE,       # skip embeddednuls
        quiet=TRUE)[-1]     # suppress length feedback & discard 1st line
   current_corpus_file <- sub( # replace
      "\t.*",                  # the first tab plus everything after it
      "",                      # by nothing
      current_corpus_file,     # in current_corpus_file
      perl=TRUE)               # using PCRE
   collector <- c(collector, current_corpus_file)
}
unlink("_inputfiles/coha_sample", recursive=TRUE)
collector %>% table %>% sort %>% tail(30)
```

### Quantifiers

You can tell R to match something only if it found a certain number of times:

* the most general uses are `{min,max}` or `{min,}` and **these quantifications apply to the immediately preceding unit**;
* there are 3 very frequent shortcuts:
   + `*` means `{0,}`;
   + `+` means `{1,}`;
   + `?` means `{0,1}`.

Here are some examples:

```{r quants}
gsub("b{1,3}",   "_", "abababbc", perl=TRUE)
gsub("b{2,3}",   "_", "abababbc", perl=TRUE)
gsub("ba{2,}",   "_", "abababbc", perl=TRUE)
gsub("(ba){2,}", "_", "abababbc", perl=TRUE)
gsub("(is )+", "_", "The thing is is that really true?", perl=TRUE)
gsub("(is )+", "_", "The thing is is that really true?", perl=TRUE)
```

Importantly, the open-ended kinds of quantification -- `{min,}` i.e. also `*` or `+` -- are **greedy**: they return the longest possible match:

```{r greedy}
gsub("[^ ]+ed=V.*[a-z]+=PART",
     "_",
     "He=PNP slipped=V up=PART and=CONJ messed=V up=PART .=PUNCT",
     perl=TRUE)
```

This matches from the *first* verb to the *second* particle/preposition and thus finds one match when we would probably want two. We need to tell R to use **lazy** matching and we can do that with a `?` after the quantifier:

```{r lazy}
gsub("[^ ]+ed=V.*?[a-z]+=PART",
     "_",
     "He=PNP slipped=V up=PART and=CONJ messed=V up=PART .=PUNCT",
     perl=TRUE)
```

#### Exercises 4

(Use this [regexr page](https://regexr.com) or [this one](https://regex101.com) if you think it helps (it usually does ...))

```{r reminderOFtxtagain}
txt <- "<w DPS>my <w NN1>mum<c PUN>, <w DPS>my <w AJ0-VVN>beloved <w NN1>aunt <w VVD>went <w PRP>into <w NN1>service"
```

* Split up the vector `txt` into words and punctuation marks using the tags:

```{r wordsANDpuncs}
unlist(                    # vectorize
   strsplit(               # the list returned when you split
      txt,                 # txt
      "<[wc] ...(-...)?>", # at every occurrence of <[wc] ...(-...)?>
      perl=TRUE))          # using Perl-compatible regular expressions
```

* What about the spaces before words? You saw above you could use `trimws` but you can also do a better split:

```{r alsospaces}
unlist(                      # vectorize
   strsplit(                 # the list returned when you split
      txt,                   # txt
      " *<[wc] ...(-...)?>", # at every occurrence of  *<[wc] ...(-...)?>
      perl=TRUE))            # using Perl-compatible regular expressions
```

* Write a regex to find all verb forms of the verb lemma REMEMBER in a corpus:

```{r remember}
"\\bremember(s|ed|ing)?\\b"
```

* Write a regex to find all verb forms of the verb LEMMA FORGET in a corpus:

```{r forget}
"\\bforg[eo]t(s|ten|ting)?\\b"
```

# Session info

```{r sessionInfo}
sessionInfo()
```
