Course introduction

Organisation, R and RStudio, and first steps in R

Dr Massimiliano Canzi

Introduction

Did you know: the aye-aye, a lemur from Madagascar, finds insect larvae by tapping on wood with its long, thin middle finger and listening for hollow tunnels. Then it gnaws a hole and hooks the larvae out with the same finger.

Source: Duke Lemur Center

Who I am

Dr Massimiliano Canzi, Max for short.

Now
Data scientist and manager of the LingLab, Universität Konstanz, since 2021
Studied
Linguistics in Milan (BA), Manchester (MA) and York (MSc); PhD in Manchester
Research
How listeners perceive speech and how speakers produce it, with experiments and quantitative methods
Also
Forensic speech science, and a lot of R

Some of my research

  • What PMN? How listeners process a phonological mismatch when the speech carries no meaning
  • Whether what we know about a speaker’s body changes how we hear their voice
  • How loud speech differs acoustically from speech at a normal level

All three needed the tools of this course: experiments with many participants and items, and regression models to make sense of them.

Who are you?

Tell us, briefly:

  • Your name and your programme
  • The data you work with, or would like to work with
  • Your experience with R: none, some, lots
  • One thing you would like to take away from this course

The course

Did you know: aye-ayes have incisors that never stop growing, like a rodent’s. No other primate has them.

Source: Duke Lemur Center

How the course works

When What happens
Lecture Fridays, 11:45 New concepts, and the code that goes with them
Tutorial Wednesdays, 13:30 You practise, with help at hand
Office hours Fridays, 10:00–11:30, by appointment Questions about the course or your own data

Announcements, homework and submissions are on Ilias.

Assessment

Component Weight
Final assignment 90%
Homework: four of the five exercises count 10%

The homework exercises are short, a few questions each, and practise what we covered in class.

The final assignment

You analyse a set of linguistic data and write it up as a scientific report of about 3000 words, in the style of an experimental paper.

You hand in one file that contains the text of your paper alongside the code of your analysis. Anyone who opens it can rerun your analysis and get the same numbers.

Your own work

  • The text and the code you submit must be your own
  • Cite every source you build on (papers, books, tutorials, code you adapt), and if in doubt, ask before you submit

As The Smiths warn in Cemetry Gates (1986): plagiarism tends to get noticed.

Dissertations

I can supervise up to two dissertations per semester as first supervisor, and up to two as second supervisor.

If you would like to write a quantitative dissertation, get in touch early.

Slides and materials

The slides are written in R Markdown and shown with reveal.js. Each week you get:

  • the slides (.html)
  • the code behind them (.Rmd)
  • the homework exercises

Open the .Rmd in RStudio and run it yourself: every number, table and plot on the slides comes from that code. Slides and code are also online, at github.com/mcanzi/ws26_statistics.

The book

Winter, B. (2019). Statistics for linguists: An introduction using R. Routledge.

  • Written for linguists, with linguistic data throughout, and uses R and the tidyverse, like this course
  • Builds everything around the linear model

Syllabus

Each lecture follows one or more chapters of Winter (2019).

Lecture Chapter
1 Course introduction 1
2 Data wrangling 2
3 Descriptive statistics 3
4 Linear models 4
5 Transformations 5
6 Multiple regression 6
7 Categorical predictors 7
Lecture Chapter
8 Interactions 8
9 Significance testing 9
10 Mixed models 1 14
11 Mixed models 2 15
12 Mixed logistic regression 12, 15.8
13 Power and model building 10, 11, 16

Getting started

Did you know: the aye-aye is the world’s largest nocturnal primate, at 2.5 to 2.8 kg. In parts of Madagascar many people see it as a bad omen (fady) that must be killed on sight.

Source: Duke Lemur Center

Software

You need two free programs:

  1. R, the language itself. Download it from CRAN
  2. RStudio, the program you write and run R code in. Download it from Posit

RStudio needs R to work, so install R first.

RStudio at a glance

Source
Your scripts and .Rmd files. Code here is saved.
Environment
The objects you have created: data sets, values, models.
Console
Where R runs your code and prints results. Code here is not saved.
Files, Plots, Packages, Help
Your folders, your plots, installed packages and the documentation.

Install the packages (once)

Type this in the RStudio Console:

install.packages(c("tidyverse", "palmerpenguins", "swirl"))

Check that everything worked:

R.version.string          # your version of R
packageVersion("dplyr")   # should be 1.2.0 or newer

You install a package once. You load it with library() in every session.

First steps in R

Did you know: the aye-aye’s thin middle finger sits on a ball-and-socket joint, like a human shoulder, so it can swivel in almost any direction while it probes for larvae.

Source: Duke Lemur Center

Hello, world

print("Hello, world!")
[1] "Hello, world!"

R is also a calculator:

2 + 2
[1] 4
10 / 4
[1] 2.5
(3 + 2) * 4
[1] 20

Brackets work as in maths: without them, 3 + 2 * 4 gives 11.

Your first script

Code typed in the Console is gone once you close RStudio. Write it in a script instead: File > New File > R Script.

# everything after a hash is a comment: R ignores it
2 + 2   # comments can also follow code
[1] 4

Run the current line with Ctrl + Enter (Cmd + Enter on a Mac). Save the script, and you can rerun the whole analysis tomorrow.

Storing values

<- stores a value in an object (read it as “gets”):

x <- 2 * 3
x
[1] 6
x + 1
[1] 7
  • The object now appears in your Environment
  • Names are case sensitive: x and X are two different objects
  • Names cannot start with a number or contain spaces: word_freq works, word freq does not

Vectors

c() combines values into a vector. Arithmetic works on every element at once:

ages <- c(23, 31, 19, 45)
ages * 12
[1] 276 372 228 540
mean(ages)
[1] 29.5

Sequences of numbers:

1:10
 [1]  1  2  3  4  5  6  7  8  9 10
seq(0, 100, by = 25)
[1]   0  25  50  75 100

Indexing

Square brackets pick out elements by position:

x <- c(4, 8, 15, 16, 23, 42)
x[1]
[1] 4
x[2:4]
[1]  8 15 16
x[-1]          # everything except the first
[1]  8 15 16 23 42

Or by a condition:

x[x > 15]
[1] 16 23 42

Logical vectors

A comparison returns TRUE or FALSE for each element:

x > 15
[1] FALSE FALSE FALSE  TRUE  TRUE  TRUE

TRUE counts as 1 and FALSE as 0, so you can count and take proportions:

sum(x > 15)    # how many?
[1] 3
mean(x > 15)   # what proportion?
[1] 0.5

Comparisons: == equal, != not equal, >, <, >=, <=

Text and categories

Text goes in "quotes": a character vector.

words <- c("cat", "dog", "cat", "bird", "cat")
table(words)
words
bird  cat  dog 
   1    3    1 

A factor stores categories, with a fixed set of levels:

animal <- factor(words)
levels(animal)
[1] "bird" "cat"  "dog" 

Levels are sorted alphabetically by default: this matters later.

Data frames

A data frame is a table whose columns are vectors of equal length:

d <- data.frame(word = c("cat", "dog", "bird"),
                freq = c(120, 95, 30))
d
  word freq
1  cat  120
2  dog   95
3 bird   30
d$freq          # one column
[1] 120  95  30
d[2, ]          # second row, all columns
  word freq
2  dog   95

Functions and arguments

A function takes arguments inside its brackets. Name them to make code readable:

round(3.14159, digits = 2)
[1] 3.14

NA marks a missing value. Most summaries return NA if one is present, unless you say otherwise:

mean(c(4, NA, 8))
[1] NA
mean(c(4, NA, 8), na.rm = TRUE)
[1] 6

Getting help

  • ?mean opens the help page for mean(): read the Arguments, and run the Examples at the bottom
  • Copy an error message into a search engine, where someone has almost always seen it before, or ask in the tutorial or in office hours

R and its packages are written by researchers. Cite them in your work:

citation()                 # how to cite R
citation("tidyverse")      # how to cite a package

swirl

swirl teaches you R, inside R. Its interactive lessons range from the basics to modelling, and some of your homework will use them (swirlstats.com).

You installed it already. To start a lesson:

library(swirl)
swirl()

The first time, swirl asks you to choose and install a course.

Inside a lesson: bye() quits and saves your progress, skip() skips a question, main() goes back to the menu.

The tidyverse

The tidyverse is a collection of R packages, created by Hadley Wickham and colleagues, for importing, reshaping and plotting data.

It replaces many base R functions with alternatives that are easier to read and write. Think of it as a dialect of R, with base R as the standard variety.

We start using it next week. It builds on everything you saw today: vectors, data frames and functions.

Statistics

Did you know: aye-ayes have a sixth finger. Next to each thumb is a small pseudothumb, with its own fingerprint, that helps them grip branches.

Source: Hartstone-Rose et al. (2019), American Journal of Physical Anthropology

Discussion

Two researchers receive the same recordings and the same research question, and analyse them independently.

  • Will they reach the same conclusion?
  • Which decisions in an analysis are the researcher’s to make?

Objective or subjective?

Coretta et al. (2023) gave one speech production data set and one research question to 46 teams of analysts.

  • The teams reported substantially different effect sizes and interpretations
  • Neither prior beliefs nor expertise explained the differences

Every analysis involves choices like these. Statistics makes them explicit, so others can check them.

What you will learn

By the end of the course you will be able to:

  • describe and plot linguistic data in R
  • build, interpret and check regression models, from simple linear models to mixed effects and logistic regression
  • report an analysis so that others can follow it and reproduce it

Your turn

Open RStudio, start a new script, and run the code from today’s slides line by line.

Then change things: other numbers, other words, a missing value. Seeing what breaks is the quickest way to learn what each piece does.

Slides and code

QR code linking to these slides

These slides

Code, data and all lectures