---
title: "Ling 120, session 03: frequency lists 1"
author:
   - name: "[Stefan Th. Gries](https://www.stgries.info)"
     affiliation:
        - UC Santa Barbara
        - JLU Giessen
     orcid: 0000-0002-6497-3958
date: "2027-01-19 12:34:56"
date-format: "DD MMM YYYY HH-mm-ss"
editor: source
format:
   html:
      page-layout: full
      code-fold: true
      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
---

# Introduction

We first clear memory, load `magrittr`, and define `just.matches`:

```{r prepworkspace}
rm(list=ls(all=TRUE)); library(magrittr)
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)
}
```

In this session, we will generate a case-insensitive frequency list of a corpus, namely the British Component of the International Corpus of English ([ICE-GB](https://www.ucl.ac.uk/english-usage/projects/ice-gb/)).

## Step 1: things we need to do

We need to

1. prepare (for) the tasks:
   a. (maybe) clear memory;
   b. (pick a corpus and) set up / define the corpus files;
   c. (maybe) define one or more collector structures;
2. implement the tasks:
   a. process each corpus file:
      i. load it;
      ii. convert it to lower case;
      iii. use regular expressions to retrieve the words from the loaded corpus file;
      iv. generate a frequency table of the words;
      v. save that frequency table somewhere;
   b. do some anal/OCD housekeeping;
   c. merge all files' frequency tables into one and check the result;
   d. output the result into a file.

## Step 2: functions we will need for that

The above tasks likely require the following functions:

1. prepare (for) the tasks:
   a. (maybe) clear memory: `XXX`;
   b. (pick a corpus and) set up / define the corpus files: `XXX` and `XXX`;
   c. (maybe) define one or more collector structures: `XXX`;
2. implement the tasks:
   a. process each corpus file: `XXX`-loop:
      i. load it: `XXX`;
      ii. convert it to lower case: `XXX`;
      iii. use regular expressions to retrieve the words from the loaded corpus file: `XXX`/`XXX` or `XXX` or `XXX` or `XXX`/`XXX`;
      iv. generate a frequency table of the words: `XXX`;
      v. save that frequency table somewhere: `XXX`;
   b. do some anal/OCD housekeeping: `XXX` and `XXX` (w/ `XXX`) and `XXX`;
   c. merge all files' frequency tables into one and check the result: `XXX` and `XXX`/`XXX`
   d. output the result into a file: `XXX`/`XXX` and `XXX`.

# Preparation
## Data structures

We first define which corpus we want to use, unzip the corresponding corpus files, and put all the file paths into a vector `corpus_files`.

```{r getcorpusfiles}
# replace this with your answers/code
corpus_files <- # replace this with your answers/code
```

In addition, we create a collector data structure `word_freqs_in_files`, each element of which will be a word frequency table for one file of the corpus; thus, this will be a list:

```{r setupcollector4freqs}
word_freqs_in_files <- # replace this with your answers/code
```

## Regex development

To generate a frequency table, we need to get the words out of the corpus files. The files of this corpus looks like this:

```{r whatthecorpuslookslike}
#| code-fold: false
noquote(current_corpus_file <- tolower(c(
   "DISMK,FRM {OK}",
   " NPHD,N(prop,sing) {Adam}",
   "DISMK,INTERJEC {uhm}",
   "PAUSE,PAUSE(short) {<,>}",
   " NPHD,PRON(inter) {what}",
   "INTOP,AUX(do,past) {did}",
   "  NPHD,PRON(pers) {you}",
   " MVB,V(cxtr,infin) {see}",
   "  P,PREP(ge) {as}",
   "  MVB,V(intr,ingp) {missing}")))
```

How could we process this? We could get the words out of there in with the following two steps:

```{r composingregex}
# replace this with your answers/code
```

# Processing
## The loop: loading, searching, interim saving

We now use a `for`-loop to

* load each file path in `corpus_files` (w/ `XXX`);
* change the words to lower case (w/ `XXX`);
* retrieve the words from the corpus file in whatever way is needed for the corpus (as per our above code);
* add the frequency table of the words from the current corpus file to the right slot of the collector list `word_freqs_in_files`;
* print a progress report (w/ `XXX`).

We will also gather two useful bits of information, namely

* measure the time it takes to do that with `system.time({...})`;
* compute the size of the collector `word_freqs_in_files` with `object.size`.

This adds virtually nothing to the processing costs or the script, but is a useful habit to get into for when you deal with more complex scripts or big data sets where scripts require optimization.

```{r mainloop}
system.time({
   # load each file path
   # replace this with your answers/code

   # retrieve the words as defined above
   # replace this with your answers/code

   # compute the frequency list and collect it:
   # replace this with your answers/code

   # output which file was just completed
   # replace this with your answers/code
}) # how fast is this?
object.size(word_freqs_in_files)
```

## House-keeping

Some house-keeping: we

* delete the unzipped corpus files (while of course retaining the zip archive);
* remove from the workspace everything but `word_freqs_in_files`:

```{r housekeeping}
# replace this with your answers/code
```

## Merging the frequency tables

Now we have a list with as many frequency tables as there were files in the corpus. We now need to 'merge' these frequency lists. For that, we first change the list into a vector (`XXX`):

```{r makecollectoravector}
# replace this with your answers/code
```

Then we get rid of the file names:

```{r removefilenames}
# replace this with your answers/code
```

And then we sum up all frequencies that belong to the same word (as per the names of the frequency). For instance, the word *the* occurs in each file and here are its frequencies in each file:

```{r sumup4the}
# replace this with your answers/code
```

What we want is combine them all -- by summing -- into one number and this is how we do it for all words at the same time:

```{r sumup4all}
all_frequencies <- # replace this with your answers/code
```

Let's check

* what the 20 most frequent words are (esp. since sorting them is a good idea anyway);
* whether the words frequencies have the expected Zipfian distribution (with two plots):

```{r checkandplot}
# replace this with your answers/code
```

## Output

All good, so we can save the result into a tab-delimited file; here are two ways to do this:

```{r output1}
# replace this with your answers/code
```
```{r output2}
# replace this with your answers/code
```

# Session info

```{r}
sessionInfo()
```
