---
title: "Ling 120, session 07: keyness w/ multiple dimensions"
author:
   - name: "[Stefan Th. Gries](https://www_stgries.info)"
     affiliation:
        - UC Santa Barbara
        - JLU Giessen
     orcid: 0000-0002-6497-3958
date: "2027-02-16 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
---

# Programming constructs 2: conditionals

Before we begin with today's corpus application, we will go over a second important programming construct, which we will need today. We will often be in the situation in which we want R to decide what to do next depending on something that happened before or that is happening elsewhere in our workspace. Several scenarios are conceivable:

1. if a condition *c* is met, do *x*, if not, do nothing;
2. if a condition *c* is met, do *x*, if not, do *y*;
3. if a condition *c* is met, do *x*, if not check whether condition *d* is met -- if yes, do *y*, if not, do *z*, etc.

The most basic way of handling conditions in R involves a control-flow structure using the expression `if`. Scenario 1 can be expressed as follows:

```{r ifscenario1}
#| eval: false
if (some_logical_expression) {
   what to do if some_logical_expression evaluates to TRUE
}
```

For example, we might want to compute the percentage distribution of the frequencies of a vector `x`, but only if `x` has 3 or more different types:

```{r generatex}
(x <- rep(2:4, 1:3)) # x has 3 types: 2, 3, 4
```

We can use the following code to let R decide whether a percentage distribution will be returned or not:

```{r ifscenario1a}
if (length(unique(x))>=3) { # if x has 3 or more unique types
   prop.table(table(x))     # then return a table of proportions
}                           # end of conditional
```

If `x` had been defined such that it had fewer than 3 types, the above conditional returns nothing:

```{r ifscenario1b}
(x <- rep(2:3, 3:4)) # x has 2 types: 2, 3
# same conditional as above:
if (length(unique(x))>=3) { # if x has 3 or more unique types
   prop.table(table(x))     # then return a table of proportions
}                           # end of conditional
# no output
```

Scenario 2 can be expressed as follows:

```{r ifscenario2}
#| eval: false
if (some_logical_expression_1) {
   what to do if some_logical_expression_1 evaluates to TRUE
} else {
   what to do if that some_logical_expression_1 evaluates to FALSE
}
```

For example, we may want to compute a measure of central tendency of a numeric vector: the mean if the vector has 30 or more elements, the median otherwise (and let's make this work properly even with vectors containing `NA`s). Remember from above that `x` currently has 7 elements:

```{r ifscenario2a}
if (sum(!is.na(x))>=30) { # if x has 30+ non-NA elements
   c("mean"=mean(x, na.rm=TRUE))     # then return the mean of those
} else {                             # otherwise
   c("median"=median(x, na.rm=TRUE)) # return the median of those
}                                    # end of conditional
```

But if `x` has enough elements that are not `NA` ...:

```{r ifscenario2b}
x <- rep(1:2, 15:16) # change x
if (sum(!is.na(x))>=30) { # if x has 30+ non-NA elements
   c("mean"=mean(x))      # then return the mean of those
} else {                  # otherwise
   c("median"=median(x))  # return the median of those
}                         # end of conditional
```

Note that I made the conditional return a named vector so that we know whether the number returned is a median or a mean.

Finally, scenario 3 can be expressed as follows:

```{r ifscenario3}
#| eval: false
if (some_logical_expression_1) {
   what to do if some_logical_expression_1 evaluates to TRUE
} else if (some_logical_expression_2) { # you can have >1 of these
   what to do if some_logical_expression_2 evaluates to TRUE
} else {
   what to do if some_logical_expression_2 evaluates to FALSE
}
```

For example, you want to log a number, but also be told explicitly if the logging 'ran into problems', i.e. when the number given to `log` was 0 or negative:

```{r ifscenario3a}
x <- 2 # change this value to see the other possible outputs
if (x>0) {                                # if x is greater than 0
   log(x)                                 # log it
} else if (x<0) {                                # if x is less than 0
   c("The number you tried to log is negative.") # return this
} else {                                  # otherwise
   c("The number you tried to log is 0.") # return this
}
```

Another conditional expression that is very useful -- especially for plotting: `ifelse`, which has the following structure:

```{r ifelse}
#| eval: false
ifelse(something_returning_TRUEs_and_FALSEs,
   what_to_return_for_each_TRUE,
   what_to_return_for_each_FALSE)
```

To see how useful this can be, let's generate some random normally-distributed numbers around 0:

```{r rndstuff}
set.seed(sum(utf8ToInt("facetiously"))) # set a replicable random number seed
summary(y <- rnorm(30))
```

Now let's plot them such that every positive number is plotted with a blue filled circle and every negative number with a red filled circle; it's extremely easy:

```{r plotrndstuff1}
plot(y,        # the y-axis values to be plotted, R then makes x be seq(y)
   pch=16,     # the point character: a filled circle
   col=ifelse( # the color is determined by ifelse:
      y>0,     # if y is great than 0, then
      "blue",  # plot the point in blue,
      "red"))  # otherwise in red
abline(h=0, lty=2) # add a dashed horizontal line at y=0
```

Now let's plot them such that we use the same color decision as above, but then also such that every `y`-value whose absolute value is greater than 1 is plotted with a filled circle whereas all others are plotted with an unfilled circle:

```{r plotrndstuff2}
plot(y, # the y-axis values to be plotted, R then makes x be seq(y)
   pch=ifelse(abs(y)>1, 16, 1),          # the character is determined by ifelse
   col=ifelse(y>mean(y), "blue", "red")) # the color is determined by ifelse
abline(            # add straight lines
   h=c(1, 0, -1),  # horizontal at these y-coordinates
   lty=c(3, 1, 3)) # dotted, solid, dotted
```

# Introduction

We first clear memory and load `magrittr`:

```{r prepworkspace}
rm(list=ls(all=TRUE)); library(magrittr)
```

This session is concerned with combining multiple dimensions of corpus measures into an analysis, something that was sometimes already hinted at in our plots of frequency vs. association or frequency vs. dispersion. As a vehicle for this, we will do a cultural keywords kind of study of keyness or keywords. **Keyness** is a notion/quantity that quantifies how key a word is for, meaning 'how characteristic a word is of', a target corpus of interest *T* relative to a (usually larger) reference corpus *R*. For example, in a language-teaching context, one might be interested in determining which words are particularly characteristic of a certain topic so that instructors have a data-driven idea of which words their students might benefit from knowing most. In an MBA program for non-native speakers of English, for instance, it might be useful to know which words from the topic area of economics/finance might be particularly useful to the students and a keywords analysis might return a list of words worthy of teaching such as this one (ordered by keyness):

*brokerage*, *tax-deferred*, *earnings*, *discounter*, *investor*, *hardcopy*, *stock*, *co-manager*, *shareholder*, *NYSE*, *annuity*, *investing*, *retailing*, *Vanguard*, *capitalization*, *profitability*, *after-tax*, *tax-free*, *bearish*, *IPO*, *company*, *portfolio*, *executive*, *holding*, *analyst*, *equity*, *dividend*, *investment*, *asset*, *firm*, *revenue*, *CEO*, *retailer*, *profit*, *salespeople*, *fund*, *small-business*, *bullish*, *merger*, *retail*, *volatility*, *profitable*, *buyout*, etc.

Keywords have mostly been identified using the log-likelihood statistic computed from a table like the one schematically represented in @tbl-schemkeyness:

|                        | Corpus: *target* | Corpus: *reference* | Sum         |
|:-----------------------|:-----------------|:--------------------|:------------|
| **Element *W*~i~**     | *a*              | *b*                 | *a+b*       |
| **Not element *W*~i~** | *c*              | *d*                 | *c+d*       |
| **Sum**                | *a+c*            | *b+d*               | *a+b+c+d=N* |

: A schematic co-occurrence table underlying nearly all keyness analyses {#tbl-schemkeyness}

But we will do this differently: we will compute three dimensions that jointly define keyness:

* frequency;
* association-based keyness using the *KLD* again: words will be considered key to the extent that they are attracted to *T* rather than *R*;
* dispersion-based keyness using the *KLD* again: words will be considered key to the extent that they are more evenly dispersed in *T* rather than in *R*.

We need to

1. prepare (for) the tasks:
   a. (maybe) clear memory: `XXX`;
   b. set up / define the corpus files: `XXX` and `XXX`;
   c. (maybe) define one or more collector structures: `XXX` or `XXX`;
2. implement the tasks:
   a. process each corpus file:
      i. load it: `XXX`;
      ii. use regular expressions to identify each word (`XXX`) as well as the corpus and the corpus part it is attested in (`XXX`, `XXX`, `XXX`);
      iii. save all this information somewhere: `XXX`;
   b. do some anal/OCD housekeeping: `XXX` and `XXX`;
   c. split up all the data into target corpus *T* and reference corpus *R*: `split`;
   d. generate the frequency component `FREQ`: `XXX`;
   e. generate the association component `XXX` by computing the *KLD*:
      i. priors;
      ii. posteriors;
      iii. signed *KLD*;
   f. generate the dispersion component `DISP` using the *KLD*s:
      i. priors in *T*, posteriors in *T*, *KLD*s;
      ii. priors in *R*, posteriors in *R*, *KLD*s;
      iii. pairwise differences;
   g. collect and amalgamate.

**Note: what I will present below is not the complete story: given the time we only have, I had to leave out a few important steps -- so, don't use just this for research but keep your eyes open for some upcoming pubs that will explain 'the full story'.**

# Preparation
## Data structures

We first define which corpora we want to compare -- Brown (AmE from the 1960s) vs. Frown (AmE from the 1990s) -- 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 three collector vectors `WORD`, `PART`, and `CORPUS` to collect all the corpus data:

```{r collectors}
WORD <- # replace this with your answers/code
PART <- # replace this with your answers/code
CORP <- # replace this with your answers/code
```

## Regex development

As for regex development, we're gonna take it easy this time and employ a so-called [**Unicode category**](https://www.regular-expressions.info/unicode.html#category). Specifically, we will use the Unicode category for 'any kind of letter from any language', which is `\\p{L}`, but we will use the opposite with a character class, one or more things that are not letters in any language: `[^\\p{L}]+`.

# Processing

As a reminder, the Brown corpus looks like this:

```{r brownexample}
noquote(tolower(c(
   "A01 0010    The Fulton County Grand Jury said Friday an investigation",
   "A01 0020 of Atlanta's recent primary election produced \"no evidence\" that",
   "A01 0030 any irregularities took place.   The jury further said in term-end",
   "A01 0040 presentments that the City Executive Committee, which had over-all",
   "A01 0050 charge of the election, \"deserves the praise and thanks of the")))
```

We cannot use the code from before because this time we'd like to be able to distinguish not just the 15 files, but the 500 corpus parts, which are represented by the first three characters of each line. And here's the Frown corpus, which has annotation between angular brackets we want to discard:

```{r frownexample}
noquote(tolower(c(
   "A01   1 <#FROWN:A01\\><h_><p_>After 35 straight veto victories, intense",
   "A01   2 lobbying fails president with election in offing<p/>",
   "A01   3 <p_>By Elaine S. Povich<p/>",
   "A01   4 <p_>CHICAGO TRIBUNE<p/><h/>",
   "A01   5 <p_>WASHINGTON - Despite intense White House lobbying, Congress has")))
```

## The loop: loading, searching, interim saving

We loop over each file name and

* load each file;
* use the line-initial annotation to associate every line with the corpus part it's from (with `paste`);
* eliminate angular-brackets annotation from FROWN;
* identify the words by splitting on non-letter characters (with `strsplit`);
* eliminate zero-character strings;
* collect everything: the words, the corpus parts they occurred in, and the corpus they occurred in in a data frame we'll call `x`;
* print a progress report.

As always, we will measure the time it takes to do that with `system.time({...})`.

```{r mainprocessing}
system.time({
for(i in seq(corpus_files)) { # access each corpus file
   # we read in each corpus file
   # replace this with your answers/code

   # name each vector element by the corpus part in which it was found
   # replace this with your answers/code

   # we remove the line-initial annotation
   # replace this with your answers/code

   # we paste everything from one corpus part together
   # replace this with your answers/code

   # if the corpus is Frown, remove the <...> annotation
   # replace this with your answers/code

   # we split up into words by everything that's not a letter character and ...
   # replace this with your answers/code

   # we get the words
   # replace this with your answers/code

   # we collect everything: words, parts, & corpora
   # replace this with your answers/code

   # progress report
   cat("\f", corpus_files[i], "\n")
} # end of for
}) # how fast is this?
head(x <- data.frame(CORP, PART, WORD))
object.size(x)
```

## House-keeping

Some house-keeping: we

* delete the unzipped corpus files (while of course retaining the zip archive);
* split `x` into the target corpus `x_tar` and the reference corpus `x_ref`;
* remove from the workspace everything we don't need anymore:

```{r housekeeping}
# replace this with your answers/code
# create target and reference corpora
x_tar <- # replace this with your answers/code
x_ref <- # replace this with your answers/code
# replace this with your answers/code
```

## The frequency component

The frequency component is easy: we'll use the logged frequency of each word type in both *T* and *R* combined (as the 'weight of evidence' we have for a word) and store that in a vector called `FREQ`:

```{r compfreq}
FREQ <- # replace this with your answers/code
```

## The association component

For the association component we'll use the *KLD* as in sessions 4 and 6. We first cross-tabulate all word types and the two corpora:

```{r prepmatrix}
# replace this with your answers/code
```

From that, we can compute the prior:

```{r assocprior}
# replace this with your answers/code
```

And the posteriors are the frequency distributions of each word type across the two corpora:

```{r assocposterior}
# replace this with your answers/code
```

Thus, we can do the exact same thing as last session for association ...

```{r compassoc1}
# replace this with your answers/code
```

... with the same small add-on: We need a signed *KLD* so we know which words diverge such that they prefer, rather than *dis*prefer *T*:

```{r compassoc2}
# replace this with your answers/code
```

Let's collect the results we have so far in a data frame `keyness` and do some housekeeping:

```{r collectclean1}
keyness <- data.frame( # replace this with your answers/code
```

Let's visualize what we have so far:

```{r plot1}
# replace this with your answers/code
```

## The dispersion component

For the dispersion component, we need to compute each word's dispersion in each corpus so we can subtract a word's dispersion in *T* from it's dispersion in *R*. We will base our dispersion calculations on the 'real' solution of session 3, which used a term-document matrix. Here we create one for each corpus:

```{r tdms}
tdm_abs_tar <- # replace this with your answers/code
tdm_rel_tar <- # replace this with your answers/code
tdm_abs_ref <- # replace this with your answers/code
tdm_rel_ref <- # replace this with your answers/code
```

This is what we just created:

```{r checktdms}
tdm_abs_tar[1:10,1:6]
tdm_rel_ref[1:10,1:6]
```

From this, we can compute the dispersion priors for each corpus, i.e. the proportional file sizes:

```{r priors}
prior_tar <- # replace this with your answers/code
prior_ref <- # replace this with your answers/code
```

Which means, we can now compute the dispersions:

```{r disps}
DISP_tar <- # replace this with your answers/code
DISP_ref <- # replace this with your answers/code
```

Here's what we now have:

```{r checkdisps}
DISP_tar %>% sort %>% head
DISP_ref %>% sort %>% head
```

Since we want high values for even dispersion, we flip the orientation of the dispersion values:

```{r flipdisps}
DISP_tar <- # replace this with your answers/code
DISP_ref <- # replace this with your answers/code
```

We now want to compute the differences `DISP_tar-DISP_ref`, but ... what's the problem now and how do we solve this? XXX

```{r computedispdiffs}
# replace this with your answers/code
keyness$DISP <- # replace this with your answers/code
```

## An amalgam

As mentioned above, I don't have time to discuss everything one can do or should with this, so I'm only going to present one way to amalgamate the three dimensions into one value:

```{r amal}
keyness$AMAL <- "+"(  # add
   keyness$DISP,      # the dispersion-based keyness to
   "*"(keyness$FREQ,  # the freqs times
       keyness$ASSC)) # the association-based keyness
keyness <- keyness[order(-keyness$AMAL),]
keyness %>% head(50) %>% rownames
```

How do we save this?

```{r savekeyness}
# replace this with your answers/code
```

As words more representative of the 1990s (relative to the 1960s), these make sense: politicians from the 1990s or that were (still) relevant in the 1990s (*Clinton*, *Reagan*, *Quayle*, *Perot*, *Bush*, *Yeltsin*, *Saddam Hussein*), terrorism-related topics big in the 1990s (*Carlos*, *terrorist*), 'activism'-related terms one might indeed expect less in written AmE of the 1960s (*gender* (see [Eskridge, Slocum, & Gries 2021](https://www.stgries.info/research/2021_WJE-BGS-STG_MeaningOfSex_MiLawRev.pdf)), *racism*, *activists*, *racist*, *feminist*), technology more obvious 1990s-related (*software*, *dna*, *receptor*, *laser*), etc.

Let's briefly visualize the correlation of `FREQ` (font size) `ASSC` (x-axis) and `DISP` (y-axis):

```{r plot2}
# replace this with your answers/code
```

# Session info

```{r}
sessionInfo()
```
