---
title: "Ling 201, session 10: outlook & recommendations"
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: 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
      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
---


```{r prepworkspace}
rm(list=ls(all=TRUE)); library(magrittr)
```

# The Chevrolet promotion data

Let's load the Chevrolet promotion data, here with one additional column (which we will ignore for now):

```{r exercise01data}
summary(d <- read.delim(
   "_input/chevyprom2.csv",
   stringsAsFactors=TRUE))
```

## Hypotheses

If you suspect Chevrolet discriminated against women, these would be the corresponding hypotheses:

* text hypotheses:
   + H~1~: XXX
   + H~0~: XXX
* statistical hypotheses:
   + H~1~: XXX;
   + H~0~: XXX.

## Descriptive stats/visualization

We first describe the data:

```{r exercise01desc}
# replace this with your answers/code
```

XXX

## Statistical testing

For this question, we would prefer to use XXX:

```{r exercise01test1}
# replace this with your answers/code
```

Clearly XXX. What is the exact *p*-value?

```{r exercise01test2}
# replace this with your answers/code
```

Note, however, that since

* XXX, and
* XXX, and
* XXX,

we could replace this with your answers/code:

```{r}
# replace this with your answers/code
```

But were we allowed to test it like this?

```{r exercise01test3}
# replace this with your answers/code
```

Thus, one would continue with XXX:

```{r exercise01test4}
# replace this with your answers/code
```

## Write-up

replace this with your answers/code

## Follow-up

But we also have departmental information, which raises important questions: XXX

* XXX
* XXX?
* XXX?

Why don't we XX. First, we XXX:

```{r exercise01followup1}
# replace this with your answers/code
```

Then, we can do this the more elegant R way ...

```{r exercise01followup2}
# replace this with your answers/code
```

... or the loop way (booo!):

```{r exercise01followup3}
#| eval: false
# replace this with your answers/code
```

So XXX?

```{r exercise01followup4}
# replace this with your answers/code
```

Oops!?

```{r exercise01followup5}
# replace this with your answers/code
```

Interesting: XXX

# The dictation data

Imagine a study that recruited students from two courses *a* and *b* to determine whether the numbers of mistakes the students made in a dictation in their native language (German) are predictive of the number of mistakes the same students made in a dictation in a language they're learning (English). Given this introduction,

* the variable `XXX` is the independent/predictor variable;
* the variable `XXX` is the response;
* the variable `XX` is XXX.

## Hypotheses

Your expectations are the following (because if someone struggles with orthography, they probably do so in both languages):

* text hypotheses:
   + H~1~: XXX;
   + H~0~: XXX;
* statistical hypotheses:
   + H~1~: XXX;
   + H~0~: XXX.

The following code loads the data (80 data points) from [_input/dictation.csv](_input/dictation.csv) (with explanations in [_input/dictation.r](_input/dictation.r)) and shows you a representative part of it:

```{r exercise02data}
rm(list=ls(all.names=TRUE))
str(d <- read.delim(       # summarize d, the result of loading
   "_input/dictation.csv", # this file
   stringsAsFactors=TRUE)) # change categorical variables into factors
d[c(1:4, 38:44),] # rows 1 to 4 and 38 to 44 of the data
```

## Descriptive stats/visualization

We describe the data:

```{r exercise02desc1}
# replace this with your answers/code
```

It looks like there's XXX ...

```{r exercise02desc2}
# replace this with your answers/code
```

For this question, we would like to use XXX:

```{r exercise02desc3}
# replace this with your answers/code
```

We can't actually use XXX -- we use XXX instead:

## Statistical testing

```{r exercise02test1}
# replace this with your answers/code
```

But it also seems as if XXX. How can you check that with what you know from Chapter 4?

You could XXX:

```{r exercise02test2}
# replace this with your answers/code
```

Because then you can XXX:

```{r exercise02test3}
# replace this with your answers/code
```

That looks so much better and appears to explain the data much better especially how we now see the difference between the two courses:

* XXX;
* XXX;
* meaning XXX.

But now here's a <font color="red">**hugely important**</font> question: XXX

# Recommendations for code

Generally, I would encourage you as strongly as possible to learn RMarkdown or, even better, Quarto, and here are some links/recommendations:

* online books:
   + [RMarkdown: The Definitive Guide](https://bookdown.org/yihui/rmarkdown/);
   + [RMarkdown Cookbook](https://bookdown.org/yihui/rmarkdown-cookbook/);
   + [RMarkdown for Scientists](https://rmd4sci.njtierney.com);
* cheatsheets etc.:
   + [cheatsheet 1](/home/sgries/Documents/Academia/Postgraduate/Rmarkdown-cheatsheet1.pdf);
   + [cheatsheet 2](/home/sgries/Documents/Academia/Postgraduate/Rmarkdown-cheatsheet2.pdf);
   + [Reference](/home/sgries/Documents/Academia/Postgraduate/Rmarkdown-reference.pdf);
* [Quarto](https://quarto.org).

But even if you followed that advice, there are still a variety of useful recommendations for how to write code (both in and outside of RMarkdown documents). Most of these you've seen used in my code, but now I'll explicate them.

```{r rec_hier}
#| eval: false
# use a hierarchical structure of comments, e.g. like this: ####
# heading 1
## heading 2
### heading 3
#### heading 4
```

For heading 1, I often end the line with 4+ # (often till column 100) like above in line 1, because that makes RStudio use the line for the outline. My heading 1 sections are often the following:

```{r rec_endofline}
#| eval: false
# preparation and exploration ####
# modeling ####
# visualization ####
```

Headings can also be statistical results so that, when you screen your code, you can see results without having to run it:

```{r rec_addresults}
#| eval: false
# poly(PREVMEAN, 3)                    3 6328.4 2379.29 < 2.2e-16 ***
ph.p <- data.frame(effect("poly(PREVMEAN, 3)", model.final, xlevels=list(PREVMEAN=seq(-2.6, 2.6, 0.25))))
ph.p$FIT <- cut(ph.p$fit, 9, labels=1:9)
# ...
```

I also often use comments to add results & thoughts into the script; in an RMarkdown document, some of these things would of course be regular text, not just comments.

```{r rec_notes}
#| eval: false
surprs[is.infinite(surprs$INF),] # 179 2768 6838 8173

r.squaredGLMM(model.final) #  R2m=0.7294388, R2c=0.7824607

sort(vif.mer(model.06a)) # <=1.505739

drop1(model.final, test="Chisq") #    Df    AIC     LRT   Pr(Chi)
# <none>                                 3955.1
# poly(PREVMEAN, 3)                    3 6328.4 2379.29 < 2.2e-16 ***
# poly(LENGTH, 2)                      2 4162.6  211.51 < 2.2e-16 ***
# poly(SURPRISAL, 2)                   2 3977.0   25.88 2.402e-06 ***
# poly(FREQ, 2)                        2 3967.7   16.67 0.0002399 ***
# poly(POSINTURN, 2):poly(NUCLEUS, 2)  4 4001.5   54.38 4.373e-11 ***

plot(m.1) # top left corner: strange bipartite structure ...
```

While R doesn't care about spaces much, I often use indentations, spacing, and super anal code alignments to guide my own parsing of code:

```{r rec_indent}
#| eval: false
# impose hierarchical structures on sequences of function calls
hist(GERMAN)
   nortest::lillie.test(GERMAN)
hist(ENGLISH)
   nortest::lillie.test(ENGLISH)

# alignment of assignment operators
surprs <- as.data.frame(surprisals); colnames(surprs) <- c("W1", "W2", "N", "D")
   surprs$N   <- as.numeric(as.character(surprs$N))
   surprs$D   <- as.numeric(as.character(surprs$D))
   surprs$INF <- -log2(surprs$N / surprs$D)

# alignment of many things
y <- data.frame(
   FILE=     factor(rep(d$FILE,    each=10)),
   SPEAKER=  factor(rep(d$SPEAKER, each=10)),
   TURN=     factor(rep(d$TURN,    each=10)),
   TURNNO=   rep(seq(nrow(x)),     each=10),
   NUCLEUS=  rep(d$NUCLEUS,        each=10),
   POSINTURN=rep(1:10, nrow(x)),
   WORD=     factor(       as.character(t(x[,18:27]))),
   POSl=     factor(       as.character(t(x[,28:37]))),
   POSs=     factor(substr(as.character(t(x[,28:37])), 1, 3)),
   LENGTH=                   as.numeric(t(x[,38:47])),
   DURATION=                 as.numeric(t(x[, 5:14]))*1000
   )
```

Then, as you have always see me do, you should break up function calls up by arguments or argument groups and annotate them well, even for things you know well (now):

```{r rec_breakup1}
#| eval: false
summary(m.1 <- lm( # fit a linear model
   ENGLISH ~ 1 +   # response ENGLISH as function of an overall intercept &
   GERMAN))        # predictor(s)

anova(m.2,   # compare m.2 to
   m.3,      # the smaller m.3
   test="F") # using an F-test: ns
```

Here are two more complex examples that also highlight changes and especially omissions in similar regression models:

```{r rec_breakup2}
#| eval: false
# example 1
summary(model.02a <- lmer(
   DURATION ~ 1 +                     # response as a function of an intercept
      poly(POSINTURN, 2) * PREVMEAN + # fixed-effect predictors
      LENGTH + SURPRISAL + FREQ + NUCLEUS + NUCLEUS:poly(POSINTURN, 2) + # controls
      (1+POSINTURN|FILE) +            # file-specific intercepts & slopes
      (1+POSINTURN|POSs),             # POSs-specific intercepts & slopes
   data=yyyy), correlation=FALSE)     # Model failed to converge with max|grad| = 0.0565417

summary(model.02b <- lmer(
   DURATION ~ 1 +                     # response as a function of an intercept
      poly(POSINTURN, 2) * PREVMEAN + # fixed-effect predictors
      LENGTH + SURPRISAL + FREQ + NUCLEUS + NUCLEUS:poly(POSINTURN, 2) + # controls
      (1          |FILE) +            # file-specific intercepts                               <---
      (1+POSINTURN|POSs),             # POSs-specific intercepts & slopes
   data=yyyy), correlation=FALSE)     # Model failed to converge with max|grad| = 0.0140501

# example 2
summary(model.01a <- lmer(
   RT ~ 1 + (GROUP + LANG + PHONOLD + ORTHOLD)^2 + # intercept & predictors
        poly(LENGTH, 2)*ZIPFFREQ +                 # controls
        (1+GROUP                   |ITEM) +   # by-item random effects
        (1+PHONOLD + ORTHOLD + LANG|SUBJECT), # by-subject random effects
   data=y), correlation=FALSE) # singular fit
   AICc(model.01a)             # 6338.132
   sort(vif.mer(model.01a))    # <84 (LENGTH)

summary(model.01b <- lmer(
   RT ~ 1 + (GROUP + LANG + PHONOLD + ORTHOLD)^2 + # intercept & predictors
        poly(LENGTH, 2)*ZIPFFREQ +                 # controls
        (1+GROUP                   |ITEM) +   # by-item random effects
        (1+          ORTHOLD + LANG|SUBJECT), # by-subject random effects                     <---
   data=y), correlation=FALSE) # tolerance warning: 0.236139
   AICc(model.01b)             # 6331.023
   sort(vif.mer(model.01b))    # <84 (LENGTH)
anova(model.01a, model.01b, refit=FALSE) # 0.9177, -> model.01b
```

And two final ones:

```{r rec_breakup3}
#| eval: false
summary(model.03c <- update(model.02, ~.
   # remove the fixef structure
   - (GROUPresc + LANGUAGE +      PHONOLDwoutORTHOLD    +      ORTHOLDwoutPHONOLD   )^2
   # and reinsert w/ a change: no more poly
   + (GROUPresc + LANGUAGE +      PHONOLDwoutORTHOLD    + poly(ORTHOLDwoutPHONOLD,2))^2),
   correlation=FALSE)
```

Here's what I once saw in a book manuscript where the authors wanted to discuss the how a model `lrMod1.1` differed from an earlier model `lrMod1`. They defined the models like so:

```{r rec_update1}
#| eval: false
lrMod1 <- glmer(stressshift ~ clabel.williams + npType.pron + voice.passive + (1 + clabel.williams + npType.pron||item) + (1 + clabel.williams + npType.pron + voice.passive||participant), data=givenness, family="binomial", control=glmerControl(optimizer = "bobyqa"))
lrMod1.1 <- glmer(stressshift ~ clabel.williams + npType.pron + (1 + clabel.williams + npType.pron|| item) + (1 + npType.pron + clabel.williams || participant), data=givenness, family="binomial", control=glmerControl(optimizer = "bobyqa"))
```

This is how I'd do that (just the `lrMod1.1`):

```{r rec_update2}
#| eval: false
lrMod1.1 <- update(lrMod1, ~.,                                   # make lrMod1.1 by updating lrMod1:
   - voice.passive,                                              # remove fixef of voice
   - (1+clabel.williams+npType.pron+voice.passive||participant)  # remove all by-part ranefs
   + (1+clabel.williams+npType.pron              ||participant)) # reinsert but not ranef of voice
```

I would also encourage you to make use of the fact that, when you label arguments, you can change their order around:

```{r rec_ordering}
#| eval: false
plot(type="n", axes=FALSE, main="The effect of GROUP:ORTHOLD",       # general
     xlab="Orthographic Levenshtein SED", x=0, xlim=c(-4, 3),        # x
     ylab="Predicted RT (Transformed)"  , y=0, ylim=c(-3.25, -0.25)) # y
   grid(); axis(1)                     # grid ...
   axis(2, at=seq(-3.25, -0.25, 0.25)) # and ...
   axis(4, at=seq(-3.25,  0.5 , 0.25)) # axes
   polygon(col="#15846630", border=NA,                   # col/border
      c(ph.go.split[[1]]$ORTHOLD, rev(ph.go.split[[1]]$ORTHOLD)), # x
      c(ph.go.split[[1]]$lower, rev(ph.go.split[[1]]$upper)))     # y
```

But the best thing is doing all the above, but in RMarkdown or, better even, Quarto -- see the other file for this session.

# Session info

```{r sessionInfo}
sessionInfo()
```
