---
title: "Ling 120, session 09: -ic/-ical adjectives"
author:
   - name: "[Stefan Th. Gries](https://www.stgries.info)"
     affiliation:
        - UC Santa Barbara
        - JLU Giessen
     orcid: 0000-0002-6497-3958
date: "2027-03-02 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: scroll
      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)
}
```

Much of corpus linguistics is based on the distributional hypothesis, here in the form provided by Harris (1970:785f.):

[i]f we consider words or morphemes A and B to be more different in meaning than A and C, then we will often find that the distributions of A and B are more different than the distributions of A and C. [...], difference of meaning correlates with difference of distribution.

In other words, the idea behind this is that distributional similarity reflects functional similarity -- semantic, discourse-functional, or other kinds of similarity. That implies words that are semantically similar tend to occur in similar lexical and grammatical contexts. For instance, the collocates -- the words you find 'around' -- the word *cat* will be more similar to the words you find around the word *dog* than to the collocates of the word *ethereal*. This distributional hypothesis has been used particularly much in studies of near synonymy, i.e. for sets of words with extremely similar meanings/functions. Would you be able to explain to a learner of English when to use *fast* vs. *quick* vs. *rapid* vs. *swift*? When to use *fatal* vs. *lethal* vs. *deadly* vs. *mortal*? Most likely not ... One way a corpus linguist could try to tease apart these near synonymous adjectives is by their collocates, namely by looking at the nouns they modify within a noun phrase. That is one of the three things we will do here for two pairs of -*ic*/-*ical* adjectives, *electric(al)* and *historic(al)*:

1. We will try to determine whether the collocates of each member of a pair (in the BNC SGML corpus files we used before) have distinctive semantic qualities that help us understand what the difference(s) between the members of a pair are; for that, we will use the *KLD* again because by now you should know it well;
2. we will test Marchand's (1969:242) claim that the forms with -*ical* are in "wider common use", which we will check
   a. by comparing the frequencies of
      i. the two members of each adjective pair in a frequency list of a larger reference corpus;
      ii. each adjective's collocates in a frequency list of a larger reference corpus;
   b. by comparing the dispersions (ranges, to be exact) of
      i. the two members of each adjective pair in a frequency list of a larger reference corpus;
      ii. each adjective's collocates in a frequency list of a larger reference corpus.

This late in the course, I am skipping the super fine-grained steps 1 and 2 -- of course you should still think things through before you start to hack something together ...

# 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 prepfiles}
# replace this with your answers/code
```

We then create a vector with all adjectives that we will want to look for. Here, we'll do that manually, but if we had more of those, we might of course load those from a file:

```{r definetargets}
adj_2_find <- c("electric", "electrical", "historic", "historical")
```

We also create a collector data structure `all_matches` that will contain all instances of these adjectives and whatever nouns that follow them:

```{r collector}
all_matches <- # replace this with your answers/code
```

## Regex development

As you may remember, the BNC SGML looks like this:

```{r bncexample1}
noquote(current_corpus_file <- tolower(c(
   "<s n=\"1553\"><w PNP>It <w VVZ>says <w PNP>he <w VVD>believed <w CJT>that <w AT0>the <w AJ0>historical <w NN1>awareness <w VM0>will <w VVI>help<c PUN>.",
   "<s n=\"2072\"><w NN1>labour <w UNC>erm <w VVG>dealing <w PRP>with <w UNC>erm <w NN1>computer <w NN2>systems <w CJC>and <w AJ0>electronic <w NN1>retrieval <w NN2>systems<c PUN>.",
   "<s n=\"2172\"><w PRP>on <w DTQ>which <w AJ0>miniature <w AJ0>electrical <w NN2>circuits <w VM0>can <w VBI>be <w VVN>created<c PUN>.")))
```

How could we process this? We look for

* a word tag (simple or portmanteau tag) that begins with the tag for an adjective in the base form (AJ0); followed by
* one of our target adjectives, followed by
* a word tag containing a tag for a noun and let's be generous and include both simple and portmanteau tags as long as their first character is an "N";
* the then next word.

Skipping over how we insert 'one of our target adjectives', we want something like this:

```{r regexicicalADJN}
# replace this with your answers/code
```

And how we insert one of our target adjectives? With `paste` ... Last thing to consider: we do also want to delete unwanted annotation, i.e. we do want to get rid of "<pause>" in this example to find *electronic retrieval*:

```{r bncexample2}
noquote(current_corpus_file <- tolower(c(
   "<s n=\"2072\"><w NN1>computer <w NN2>systems <w CJC>and <w AJ0>electronic <pause> <w NN1>retrieval <w NN2>systems<c PUN>.")))
```

# Processing
## The loop: loading searching, interim saving

Let's now loop over each file and proceed as discussed above:

```{r mainprocessing1}
system.time({ # measure the time of everything that follows
for(i in seq(corpus_files)) { # access each corpus file
   # replace this with your answers/code

   # use only the sentence-tagged lines of the corpus file
   # replace this with your answers/code

   # filter out unwanted annotation
   # replace this with your answers/code

   for (j in adj_2_find) { # for once, I am deviating from the more flexible for (j in seq(adj_2_find))
      # put together the regex for the current adjective
      # replace this with your answers/code

      # look for it in current_sentences & trim whitespace
      # replace this with your answers/code

      # add to previous matches
      # replace this with your answers/code

      # output which file and adjective were just completed
      # replace this with your answers/code
   } # end of for j
} # end of for i
}) # how fast is this?
object.size(all_matches)
```

## House-keeping

```{r housekeeping}
# replace this with your answers/code
```

## Isolate adjectives and nouns

We now want extract the adjectives and the nouns from `all_matches`. Here are two good ways to do this for the kind of result we have in `all_matches`.

### Approach 1: searching and replace

This is how we could get the adjectives with a nice search:

```{r getadj1}
head(all_adj <- # replace this with your answers/code
```

And this is how we could get the nouns with an easy replacement:

```{r getn1}
head(all_n <- # replace this with your answers/code
```

### Approach 2: string-splitting

We first split up at tags ...

```{r getboth1}
head(all_matches_split <- # replace this with your answers/code
```

... and then we extract what we want:

```{r getboth2}
head(all_adj <- sapply(# replace this with your answers/code
head(all_n <- sapply(# replace this with your answers/code
```

### Store in one nice data frame

Let's put this all into a data frame for ease of keeping things together and also a list `result_split` with a separate data frame for each adjective pair:

```{r collectresults}
result <- data.frame(# replace this with your answers/code
result_split <- # replace this with your answers/code
lapply(          # apply to each element of
   result_split, # the split-up list
   head,         # the function head &
   10)           # show the first 10 rows
```

## Statistical analyses

Let's now analyze the results statistically; we begin with the distinctive collocates.

### Computing distinctive collocates

Let's first create a list that will collect the distinctive collocates for each adjective pair; we'll call it `collector_distcoll`:

```{r collector4collocates}
collector_distcoll <- # replace this with your answers/code
```

Now we go over each adjective pair:

* we grab the data frame for an adjective pair;
* we cross-tabulate the noun collocates with the two adjectives of a pair into a table called `curr_coll_by_adj`;
* we again compute the signed *KLD* to measure how much each collocate (dis)prefers each adjective:
   + we compute the prior from the `colSums` of `curr_coll_by_adj`;
   + we compute the posteriors from each row of `curr_coll_by_adj`;
   + we compute the *KLD* as before and ...
   + sign it as before;
* we collect the values in the right slot of our collector list `collector_distcoll`:

```{r computeKLDs}
for (i in seq(result_split)) {
   # we grab the data for the current adjective pair:
   # replace this with your answers/code

   # we compute a collocate-by-adjective co-occurrence table/matrix:
   # replace this with your answers/code

   # we compute the prior for this adjective pair:
   # replace this with your answers/code

   # we compute the posteriors for this adjective pair:
   # replace this with your answers/code

   # we compute the unsigned KLD-values:
   # replace this with your answers/code

   # make them signed (>0 -> -ic, <0 -> -ical)
   # replace this with your answers/code

   # save the results
   # replace this with your answers/code
}; collector_distcoll
```

### Comparing adjective frequencies and ranges

Now let's test Marchand's claim that -*ical* forms are in wider common use. We load the complete frequency list of (an older version of) the whole British National Corpus, which contains the frequencies of all word types in the BNC (in a column called `FREQUENCY`) and very crude dispersion information (range, in a column called `FILES`):

```{r loadreftable}
summary(freqs_BNC <- # replace this with your answers/code
head(freqs_BNC)       # check the input
object.size(freqsBNC) # 64,280,352
```

What are the frequencies of our adjectives? We first downsize the frequency data frame to one that contains only adjectives and then we look up our four adjectives of interest in there:

```{r data4ouradj}
freqs_BNC_adj <- # replace this with your answers/code
```

Is Marchand supported? # replace this with your answers/code

### Comparing collocate frequencies and ranges

Since now we're interested in the nouns, but also many of them, let's reduce the memory footprint to what we need, namely only the nouns:

```{r focusonnouns}
# replace this with your answers/code
object.size(freqs_BNC_n) # 29,660,448, much smaller than original
```

One way to check things now would be to return our two data frames in `result_split`; here's what those looked like:

```{r reminderofresultssplit}
lapply(result_split, head)
```

The beginning is actually really simple -- the rest not so much, I have to admit ... As before, we begin with two collector structures. We create one list that will collect the collocates' frequencies (`collector_freqcoll`) and another that will collect the collocates' ranges (`collector_rangcoll`):

```{r collectors4freqANDrange}
collector_freqcoll <- collector_rangcoll <- # replace this with your answers/code
```

Now we go over each adjective pair:

* we grab the data frame for an adjective pair (as before);
* we cross-tabulate the noun collocates with the two adjectives of a pair into a table called `curr_coll_by_adj` (as before);
* now the difficult part~1~: we convert that into a table that has
   + `TRUE`/1 when the collocate is attested with the adjective;
   + `FALSE`/0 when it isn't;
* now the difficult part~2~: we multiply these 1s and 0s with
   + the frequencies of the collocates from the BNC in `freqs_BNC_n`;
   + the ranges of the collocates from the BNC in `freqs_BNC_n`;
* we collect the values in the right slot of our collector lists `collector_freqcoll` and `collector_rangcoll`:

```{r computecollocfreqsANDranges}
for (i in seq(result_split)) {
   # we grab the data for the current adjective pair:
   # replace this with your answers/code

   # we compute a collocate-by-adjective co-occurrence table/matrix:
   # replace this with your answers/code

   # we change this into a matrix of TRUEs/FALSEs (because those are 1s/0s)
   # replace this with your answers/code

   # look up the collocates frequencies & save the results:
   collector_freqcoll[[i]] <- # replace this with your answers/code

   # look up the collocates ranges & save the results:
   collector_rangcoll[[i]] <- # replace this with your answers/code
}
```

And then we evaluate again. How might we analyze these data statistically (with a very simple approach), and how might we plot them?

```{r statsONfreqs}
# replace this with your answers/code
```
```{r plotsONfreqs}
# replace this with your answers/code
```
```{r statsONranges}
# replace this with your answers/code
```
```{r plotsONranges}
# replace this with your answers/code
```

# Session info

```{r}
sessionInfo()
```
