---
title: "Ling 120, session 10: prenominal adjective order"
author:
   - name: "[Stefan Th. Gries](https://www.stgries.info)"
     affiliation:
        - UC Santa Barbara
        - JLU Giessen
     orcid: 0000-0002-6497-3958
date: "2027-03-09 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 & preparation

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 the previous sessions, we dealt with the four basic corpus-linguistic methods -- frequency lists, dispersion, association/keywords, and concordancing -- and we did that mostly from the perspective of base R. In this final script, we are going to explore a few things that go beyond that and that synthesize several things we have done already with functionality that other packages offer; that of course means that I cannot discuss these other packages much -- the point here is to give you a flavor of a more comprehensive application. What we will do is explore the question of which of several factors determine the order of two adjectives used prenominally in the writing of learners of English in the (untagged) Swedish component of [ICLE](https://uclouvain.be/en/research-institutes/ilc/cecl/icle.html).

The factors we will study are

* the **lengths of the adjectives** (because it has been found that [shorter adjectives precede longer ones](https://www.researchgate.net/profile/Stefanie_Wulff/publication/233703570_A_multifactorial_corpus_analysis_of_adjective_order_in_English/links/55226ad60cf29dcabb0d5084/A-multifactorial-corpus-analysis-of-adjective-order-in-English.pdf));
* the **frequency of the adjectives** (because it has been found that [more frequent adjectives precede less frequent ones](https://www.researchgate.net/profile/Stefanie_Wulff/publication/233703570_A_multifactorial_corpus_analysis_of_adjective_order_in_English/links/55226ad60cf29dcabb0d5084/A-multifactorial-corpus-analysis-of-adjective-order-in-English.pdf));
* the **sentiment of the adjectives** (because it has been hypothesized that 'happier/better' words precede 'worse' ones, the [Pollyanna Hypothesis](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.475.4715&rep=rep1&type=pdf)).

Finally, we will quickly check whether the presence of any such effects might be related to the proficiency of the learners who wrote the essays in the corpus; that proficiency will be operationalized via

* a **readability** score ([Flesch's Reading Ease Score](https://en.wikipedia.org/wiki/Flesch–Kincaid_readability_tests#Flesch_reading_ease): the lower the score, the more complex the text);
* a **lexical diversity** score ([Moving-Average Type-Token Ratio](https://www.tandfonline.com/doi/abs/10.1080/09296171003643098)): the higher the score, the more lexical diversity.

We will proceed as follows:

1. Since the learner corpus is not tagged, if we want to find Adj-Adj-N sequences, we will first POS-tag the learner data (using the libraries `NLP` and `openNLP`);
2. we will then use the tags to retrieve Adj-Adj-N sequences (w/ `just.matches`) plus we will do a bit of post-processing the data to get them into shape for the subsequent analyses;
3. then, we will study the above variables:
   - length (which we will get from our data w/ `nchar`);
   - frequency (which we will get from frequency lists compiled in Session 5 of the course);
   - sentiment values (which we will get from the package `syuzhet`).
4. finally, we will compute for each learner essay the readability score and the lexical diversity score (which we will get from the package `quanteda`) to see whether those are related to the above predictors.

We unzip and define the corpus files from the learner corpus:

```{r prepfiles}
unzip("_inputfiles/icle2-sw.zip", # unzip this zip archive
      exdir="_inputfiles")        # into the "_inputfiles folder/directory

corpus_files <- dir( # make corpus_files the content of the directory
   "_inputfiles/icle2-sw", # <_inputfiles/icle2-sw>
   recursive=TRUE,   # browse all sub-folders
   full.names=TRUE)  # keep full path information
```

# Processing
## Tag each corpus file and retrieve Adj-Adj-N sequences

To tag the corpus texts and immediately also do the concordancing, we first set up a cluster of cores/threads:

```{r setupcluster}
library(doParallel)       # load the required library
registerDoParallel(       # register a cluster that R knows about
   cl <-                  # under the name cl
      makePSOCKcluster(   # which is a cluster that
         detectCores()-1, # will utilize all cores/threads you have available but 1
         outfile=""))     # but still returns printed progress reports to the main console
```

Then, we employ the following multi-step strategy: we

* load the packages `openNLP` and `NLP`;
* load each file in the usual way (w/ `scan`) and convert to a string (in the `NLP` sense);
* generate the required annotators and find the tags for each word;
* generate tag-word pairs with angular brackets (w/ `sprintf`) and merge them into a new tagged corpus file (w/ `paste`);
* we use `just.matches` to find adjective-adjective-noun sequences with context;
* if there are matches, we add the file name to the output and collect the results in `all_matches`:

```{r mainprocessing1}
#| warning: false
#| output: false
library(NLP); library(openNLP) # load the required libraries
system.time({ # time the following process
all_matches <- # make all_matches the result of doing w/ a cluster
   foreach(i=seq(corpus_files),
           .combine=c,
           .packages=c("dplyr", "NLP", "openNLP")
           ) %dopar% { cat(".")

      curr_string <-                                           # make curr_string the result of
         scan(corpus_files[i], what=character(), sep="\n",           # loading the current file
              quote="", comment.char="", quiet=TRUE, fileEncoding="ISO-8859-1") %>%   # w/ the usual corpus file loading settings
         "["(-1) %>% as.String            # removing the first element and making it a 'string'

      # generate annotators that openNLP requires
      sent_token_annotator <- Maxent_Sent_Token_Annotator()
      word_token_annotator <- Maxent_Word_Token_Annotator()
      pos_tag_annotator <- Maxent_POS_Tag_Annotator()

      # assign part-of-speech annotation
      pos_annotation <- annotate(
         s=curr_string,       # a string object
         f=pos_tag_annotator, # an annotator object
         annotate(            # an annotation object
            curr_string,      # this current string, now
            list(sent_token_annotator,   # sentence-tokenized
                 word_token_annotator))) # word-tokenized

      # generate words & tags
      curr_words_pointer <- subset(pos_annotation, type=="word")
      curr_tags <- sapply(curr_words_pointer$features, "[[", "POS")
      curr_words <- curr_string[curr_words_pointer]

      # generate tagged corpus file:
      sprintf("<%s>%s",          # put angular brackets 'thing'1 immediately before 'thing'2:
                 curr_tags,      # 'thing'1
                 curr_words) %>% # 'thing'2
      paste(collapse=" ")    ->  # paste together all word-tag pairs and dump the string into
      current_tagged_file        # current_tagged_file

      # retrieve Adj-Adj-N sequences, ...
      curr_matches <- just.matches(
         "(?x)                 # free-spacing
            <JJ[RS]?>          # something tagged as an adjective
            [^<]+              # that adjective
            <JJ[RS]?>          # something tagged as an adjective
            [^<]+              # that adjective
            <N[^>]+?>          # something tagged as a noun
            [^<]+              # that noun
            ",
         current_tagged_file,  # in current_tagged_file
         ignore.case=TRUE) %>% # case-insensitively &
         trimws                # trim whitespace

      if (length(curr_matches)>0) {          # if there are matches,
         curr_matches <-                     # make curr_matches
            paste(basename(corpus_files[i]), # the result of prefixing the file name
                  curr_matches,              # in front of curr_matches
                  sep="\t")                  # with a tabstop in-between
      }

      curr_matches # 'return' to all_matches
   } # end of foreach
}) # approx. 29 seconds (with 23 threads)
stopCluster(cl)
detach(package:doParallel); detach(package:NLP); detach(package:openNLP)
invisible(gc())
```

## Postprocessing for subsequent analysis

We first output the results into a spreadsheet-like tab-delimited .csv file with the usual kind of `cat` application:

```{r interimoutput1}
cat( # replace this with your answers/code
    file="_outputfiles/218_10_conc1.csv")
```

But then, we load it again into a data frame `x` for some post-processing (w/ `read.table`):

```{r interimloadagain1}
summary(x <- read.table(
   "_outputfiles/218_10_conc1.csv",
# replace this with your answers/code
head(x)
```

Specifically, we want to get rid of the part-of-speech tags that we now don't need anymore, plus we want easy access to the adjectives. Thus, we can proceed like we did last week (approach 2 in Section 3.3.2): we first use the tags to split things up nicely and the use `sapply` with the function `[` to access our elements of interest:

```{r getcomponents}
# replace this with your answers/code
```

After that, we save the file again so that now we have a neatly organized spreadsheet for further processing:

```{r interimoutput2}
write.table(x, file="_outputfiles/218_10_conc2.csv",
   # replace this with your answers/code
```

## Analysis of several predictors

Now we explore the effects of the above-mentioned predictors. We load the file again so we have the right columns lined up:

```{r interimloadagain2}
str(x <- read.table(
   "_outputfiles/218_10_conc2.csv",
# replace this with your answers/code
```

### Is there a length effect?

Obviously, we begin by computing the lengths of the adjectives in characters:

```{r lengths}
x$ADJ1LENGTH <- # replace this with your answers/code
x$ADJ2LENGTH <- # replace this with your answers/code
```

A quick monofactorial plot suggests that there is a significant length effect: there seems to be a greater number of cases where adjective 2 is longer than adjective 1:

```{r lengthsplot}
# replace this with your answers/code
```

But is it significant? How do we even check this? Back to 104/201, if you have taken that: a one-tailed Wilcoxon-test or the equivalent one-sample signed rank test:

```{r lengthstest}
qwe <- # replace this with your answers/code
```

There is a significant difference such that adjective 2 is longer (*V*=`r qwe$statistic`, *p*=`r qwe$p.value`).

### Is there a frequency effect?

We load two frequency lists that we hopefully created before in the course: one from the Brown corpus and one from the ICE-GB:

```{r loadfreqlists}
head(freq_brown <- read.delim("_outputfiles/218_04_freqlists_brown_tagged.csv", stringsAsFactors=TRUE))
head(freq_icegb <- read.delim("_outputfiles/218_03_freqlists_icegb.csv"       , stringsAsFactors=TRUE))
```

We merge the two data frames, each of which represents a frequency per 1 million words, into one (w/ `rbind`) and then compute the combined frequencies per million words by average:

```{r freqs}
freqs <- # replace this with your answers/code
freqs_pmw <- # replace this with your answers/code
```

Then, we do OCD housekeeping and delete the original frequency lists, but add the frequencies we just generated to the data frame for each of the two adjectives:

```{r addfreqs2data}
# replace this with your answers/code
x$ADJ1FREQ <- # replace this with your answers/code
x$ADJ2FREQ <- # replace this with your answers/code
```

Careful, though: not all adjective forms in our data are attested in the reference corpora. This can always happen, but is especially to be expected here given that we tagged the corpus (which comes with errors) and this is learner writing, which comes with additional errors):

```{r carefulunattested}
list("Unattested adjectives 1"=x[is.na(x$ADJ1FREQ),"ADJ1"] %>% sort,
     "Unattested adjectives 2"=x[is.na(x$ADJ2FREQ),"ADJ2"] %>% sort)
```

Using the data we do have, a quick monofactorial plot seems to suggest that there is a highly significant frequency effect:

```{r freqsplot}
# replace this with your answers/code
```

This is not unexpected, given that usually, length and frequency are inversely correlated. In our current data, the (Pearson product-moment) correlations between logged frequency pmw and length are surprisingly strong: `r round(cor(log2(x$ADJ1FREQ), x$ADJ1LENGTH, use="complete.obs"), 3)` for adjective 1 and `r round(cor(log2(x$ADJ2FREQ), x$ADJ2LENGTH, use="complete.obs"), 3)` for adjective 2. Is there a significant difference as expected?

```{r freqstest}
qwe <- # replace this with your answers/code
```

A one-tailed Wilcoxon-test or the equivalent one-sample signed rank test show highly significant differences in the expected direction of adjective 1 being more frequent (*V*=`r qwe$statistic`, *p*=`r qwe$p.value`).

### Is there a Polyanna effect?

We load the package [syuzhet](https://cran.r-project.org/web/packages/syuzhet/index.html), which provides easy access to sentiment values:

```{r loadsyuzhet}
library(syuzhet)
```

Then, we retrieve sentiment values for our adjectives and add them to the data frame for each of the two adjectives:

```{r sents}
x$ADJ1SENT <- # replace this with your answers/code
x$ADJ2SENT <- # replace this with your answers/code
```

A quick monofactorial plot doesn't seem to suggest a significant Polyanna effect:

```{r sentsplot}
# replace this with your answers/code
```

Hard to see much of a pattern there ... is it significant?

```{r sentstest}
qwe <- # replace this with your answers/code
```

A one-tailed Wilcoxon-test or the equivalent one-sample signed rank test shows a significant difference in the expected direction of adjective 1 being more positive  (*V*=`r qwe$statistic`, *p*=`r qwe$p.value`).

Housekeeping:

```{r detachsyuzhet}
detach(package:syuzhet)
```

## But is proficiency a moderator?

We load a package that provides easy access to readability and lexical diversity statistics:

```{r loadquantedas}
#| message: false
library(quanteda)
library(quanteda.textstats)
```

We create collector vectors to collect the readability-scores (Flesch's Reading Ease Score) and the lexical diversity scores (Moving-Average Type-Token Ratio) for each essay:

```{r profcollectors}
FKs <- LDs <- # replace this with your answers/code
```

Now we have to load the original corpus files again, but note: we don't need to load all of them - we only need to load and process those that contributed concordance data. Thus, we

* access a file name from all file names of ICLE-SW;
* check whether that file is actually represented in the concordance output -- if not, we don't do anything;
* if yes, we load the file and make it one long character string and then we compute our two measures:

```{r computeproficiencies}
system.time({
for (i in seq(corpus_files)) {
   # if the current corpus file to be loaded didn't actually have concordance matches, just iterate
   if (!(basename(corpus_files[i]) %in% unique(x$FILE))) { next }

   # otherwise, load it and prepare it
   curr_corp_file <-                                    # make curr_corp_file the result of
      scan(corpus_files[i], what=character(), sep="\n", # loading the current file
           quote="", comment.char="", quiet=TRUE) %>%   # w/ the usual corpus file loading settings
      "["(-1)                                     %>%   # removing the first element
      paste(collapse=" ")

   # compute the Flesch-Kincaid score and save it for the relevant file name
   FKs[basename(corpus_files[i])] <- as.numeric(textstat_readability(curr_corp_file)[1,2])

   # compute the MAATS diversity score and save it for the relevant file name
   LDs[basename(corpus_files[i])] <- as.numeric(textstat_lexdiv(
      tokens(curr_corp_file),
      measure="MATTR")[1,2])
} })["elapsed"] # around 38 seconds
```

After having computed the values, we insert them into the data frame `x` in the right (file-wise) positions; while doing so, we plot two quick histograms as well and 'clean up':

```{r profs}
x$FK <- # replace this with your answers/code
x$LD <- # replace this with your answers/code
# house-keeping
# replace this with your answers/code
```

Are these two measures (negatively) related? One would think so ...

```{r profscorr}
# replace this with your answers/code
```

Wow, ok, not much ... But let's now do a quick-and-dirty check whether these measures are related to the above differences we found between adjective 1 and 2.

### Proficiency and length

We fit a model regressing the length differences on the two proficiency approximators (as polynomials to the second degree) and their interaction:

```{r lengAFAprof}
# replace this with your answers/code
```

Just about significant, ok, but the effect size (*R*^2^) is miserably small.

### Proficiency and frequency

We fit a model regressing the frequency differences on the two proficiency approximators (as polynomials to the second degree) and their interaction:

```{r freqAFAprof}
# replace this with your answers/code
```

Nothing ...

### Proficiency and sentiment

We fit a model regressing the sentiment differences on the two proficiency approximators (as polynomials to the second degree) and their interaction:

```{r sentAFAprof}
# replace this with your answers/code
```

Nada ...

## Conclusion

We found prenominal adjective ordering in the writing of intermediate-to-advanced Swedish learners of English to be

* # replace this with your answers/code
* # replace this with your answers/code
* # replace this with your answers/code

As for proficiency differences, # replace this with your answers/code

# Where to go from here

The next four things you should consider are

* working through my book for all the basic and intermediate stuff;
* reading up on parallelizing things (with things like `doParallel::foreach` and/or `parallel::parSapply` etc.); `doParallel` is [here](https://cran.r-project.org/package=doParallel);
* reading up on dedicated packages such as
   - `udpipe` for "'tokenization', 'parts of speech tagging', 'lemmatization' and 'dependency parsing' of raw text"; the package is [here](https://cran.r-project.org/package=udpipe) on CRAN;
   - `openNLP` for "tokenization, sentence segmentation, part-of-speech tagging, named entity extraction, chunking, parsing, and coreference resolution"; the package is [here](https://cran.r-project.org/package=openNLP) on CRAN;
   - `tm` for "text mining applications"; the package is [here](https://cran.r-project.org/package=tm) on CRAN;
* reading my upcoming book on tupleization and all sorts of *KLD* applications, once it's out.

More generally, that means checking out the CRAN Task Views on [high-performance and parallel computing with R](https://cran.r-project.org/web/views/HighPerformanceComputing.html) and [Natural Language Processing](https://cran.r-project.org/web/views/NaturalLanguageProcessing.html).

# Session info

```{r}
sessionInfo()
```
