DAPR2 Lab Exercises
  • Block 1: Intro LM
    • 01: Simple linear regression
    • 02: Multiple regression
    • 03: Significance tests
    • 04: Model comparison
    • 05: Practice write-up
  • Block 2: Extending LM
    • 06: Treatment coding
    • 07: Sum coding
    • 08: Assumptions and diagnostics
  • Block 3: Interactions
  • Block 4: Logistic regression

On this page

  • Set up and plot data
  • Set up sum coding
  • Think ahead to model interpretation
  • Fit and interpret the model
  • Choosing coding schemes for different RQs
  • Optional: Knit your report to PDF

07: Sum coding

This week, you’ll run an analysis using a three-level sum-coded categorical predictor, while also controlling for a continuous numeric covariate.

NoteGet set up
  1. Open RStudio.
  2. Create a new .Rmd file for this week’s exercises.
  3. Save it somewhere you can find it again.
  4. Give it a clear name (for example, dapr2_lab07.Rmd).
  5. In the first code chunk, load the packages you’ll need this week (and install them if you don’t have them already):
    • tidyverse

RQ: Controlling for people’s pre-existing anxiety levels, is coughing before a lie detector test significantly associated with a lower-than-average heart rate during the test? (Apparently coughing is a way to immediately lower heart rate!)

Data dictionary:

variable description
age Age of participant (years)
anx Anxiety measure (z-scored)
strategy Pre-test calming strategy (CloseEyes, Cough, DeepBreath)
hr Average heart rate (in bpm, beats per minute) during test
NoteMore detail about this dataset

Law enforcement in some countries regularly rely on ‘polygraph’ tests as a form of ‘lie detection’. These tests involve measuring heart rate, blood pressure, respiratory rate and sweat. However, there is very little evidence to suggest that these methods are remotely accurate in being able to determine whether or not someone is lying.

Researchers are interested in if peoples’ heart rates during polygraph tests can be influenced by various pre-test strategies, including deep breathing, or closing their eyes. They recruited 142 participants (ages 22 to 64). Participants were told they were playing a game in which their task was to deceive the lie detector test, and they would receive financial rewards if they managed successfully. At the outset of the study, they completed a questionnaire which asked about their anxiety in relation to taking part. Participants then chose one of three strategies to prepare themselves for the test, each lasting one minute. These were “deep breathing”, “close your eyes”, or “cough”. Then the average heart rate of each participant was recorded during their lie detector test.

Set up and plot data

Question 1

Read in the data from https://uoepsy.github.io/data/polygraph.csv and store it in a variable named heartrate.

Solution

Solution 1.

heartrate <- read_csv('https://uoepsy.github.io/data/polygraph.csv')

Question 2

Make a violin plot (including jittered points and group means) to show the distribution of heart rate hr values for each pre-test calming strategy.

🗂️ See Exploring data visually > Violin plot flash card.

Solution

Solution 2.

heartrate |>
  ggplot(aes(x = strategy, y = hr, fill = strategy, colour = strategy)) +
  geom_violin(alpha = 0.5) +
  geom_jitter(height = 0, alpha = 0.5) +
  stat_summary(fun = mean, geom = 'point', colour = 'black', size = 3) +
  theme(legend.position = 'none') +
  labs(
    y = 'Heart rate (bpm)',
    x = 'Calming strategy'
  )

Set up sum coding

Question 3

First, convert strategy into a factor (don’t worry about ordering levels of the factor).

TipCode hint

For a dataframe df with a column called variable, the following code will take that column and change it into a factor.

df <- df |>
  mutate(
    variable = factor(variable)
  )

Then, run the following code to show the default contrast matrix that R would use if we used strategy as a predictor right now:

contrasts(heartrate$strategy)

Write down: What contrast coding scheme does this contrast matrix represent?

Solution

Solution 3.

heartrate <- heartrate |>
  mutate(
    strategy = factor(strategy)
  )
contrasts(heartrate$strategy)
           Cough DeepBreath
CloseEyes      0          0
Cough          1          0
DeepBreath     0          1

This contrast coding scheme is treatment coding, which we got to know last week.

By default, R will always treatment-code a categorical predictor unless we tell it otherwise.

Question 4

Apply sum coding to the strategy variable using the function contr.sum().

🗂️ See Sum coding > Define sum coding flash card.

After using contr.sum(), copy and run the following code to give the dummy variables—the columns of the contrast matrix—more useful names that tell you which level is coded as 1 in each variable. You don’t need to know what all the bits of this code mean (unless you want to!).

dimnames(contrasts(heartrate$strategy))[[2]] <- c('CloseEyes', 'Cough')

Finally, generate the contrast matrix for strategy again. Verify that it looks the way you’d expect: do the column names match up with the values labelled 1 in each dummy variable?

Solution

Solution 4.

contrasts(heartrate$strategy) <- contr.sum(3)
contrasts(heartrate$strategy)
           [,1] [,2]
CloseEyes     1    0
Cough         0    1
DeepBreath   -1   -1

For the first dummy variable, CloseEyes is coded as 1, and for the second, it’s Cough. So:

dimnames(contrasts(heartrate$strategy))[[2]] <- c('CloseEyes', 'Cough')

Sense check:

contrasts(heartrate$strategy)
           CloseEyes Cough
CloseEyes          1     0
Cough              0     1
DeepBreath        -1    -1

Good!

Think ahead to model interpretation

Question 5

This is a conceptual/interpretation question—no coding needed.

The model we fit later will have two coefficients which correspond to the strategy variable: strategyCloseEyes and strategyCough. (We know this because there are two columns in the contrast matrix we generated above, and two columns \(\rightarrow\) two dummy variables \(\rightarrow\) two coefficients.)

For each of these two sum-coded slope coefficients, write a brief sentence that describes what each coefficient will mean/represent.

Decide: Which one of those coefficients will help you address the research question?

🗂️ See Sum coding > Model fit and interpretation flash card.

Solution

Solution 5.

  • strategyCloseEyes: Estimated heart rate when strategy = CloseEyes minus the grand mean heart rate.
  • strategyCough: Estimated heart rate when strategy = Cough minus the grand mean heart rate.

Well, those are the interpretations if our model were just hr ~ strategy, without controlling for anx!

In a model that does include anx as a covariate, hr ~ strategy + anx, the interpretations become:

  • strategyCloseEyes: Estimated heart rate when strategy = CloseEyes minus the grand mean heart rate, holding anxiety constant.
  • strategyCough: Estimated heart rate when strategy = Cough minus the grand mean heart rate, holding anxiety constant.

Now, for the question of which coefficient addresses the RQ. Let’s remind ourselves of the research question: Controlling for people’s pre-existing anxiety levels, is coughing before a lie detector test significantly associated with a lower-than-average heart rate during the test?

  • The coefficient that will let us address this RQ is strategyCough, which looks exactly at what we want to know: the difference between the heart rate after coughing and the overall average (grand mean) heart rate, holding anxiety constant (and thus controlling for anxiety).

Question 6

This is a conceptual/interpretation question—no coding needed.

The RQ specifies that we must control for people’s pre-existing anxiety levels, which are contained in the continuous numeric variable anx. Therefore, we’ll include anx as a predictor in our model, and we’ll get a coefficient estimate for anx.

Think back to Block 1 and write a brief sentence about what the anx coefficient will mean/represent.

🗂️ See Multiple regression flash card.

Solution

Solution 6. Recall that anx has been z-scored, so anx = 0 represents mean anxiety, and anx = 1 represents one SD above the mean.

anx: Holding strategy constant (you can think of this as averaging over all strategies), how much the average heart rate is estimated to increase/decrease when anx increases by one SD.

Question 7

Write out the mathematical formulation of the model we will fit.

Hint: Your model should have three predictors. You can revisit the last couple questions to identify what the predictors should be.

🗂️ See Sum coding > Mathematical model formulation flash card.

Solution

Solution 7. \[ \text{heart rate} = \beta_0 + (\beta_1 \cdot \text{strategy}_\text{CloseEyes}) + (\beta_2 \cdot \text{strategy}_\text{Cough}) + (\beta_3 \cdot \text{anx}) + \epsilon \]

Fit and interpret the model

Question 8

Fit this linear model in R and name it hr_mdl.

Display the model summary.

🗂️ See Sum coding > Model fit and interpretation flash card.

Solution

Solution 8.

hr_mdl <- lm(hr ~ strategy + anx, data = heartrate)
summary(hr_mdl)

Call:
lm(formula = hr ~ strategy + anx, data = heartrate)

Residuals:
    Min      1Q  Median      3Q     Max 
-8.7146 -3.4269 -0.3907  3.0082 11.5010 

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)        53.9153     0.4897 110.103  < 2e-16 ***
strategyCloseEyes   3.0337     0.7769   3.905 0.000165 ***
strategyCough      -0.8445     0.6502  -1.299 0.196767    
anx                 3.3982     0.7432   4.573 1.29e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.567 on 108 degrees of freedom
Multiple R-squared:  0.1749,    Adjusted R-squared:  0.152 
F-statistic: 7.631 on 3 and 108 DF,  p-value: 0.0001127

Question 9

This is a conceptual/interpretation question—no coding needed.

Write a sentence for each coefficient estimated by the model to interpret/explain what it means.

Bonus: Try to describe in your own words why the intercept means something different for treatment coding and for sum coding.

🗂️ See Sum coding > Model fit and interpretation flash card.

Then, write one sentence that answers the RQ.

Bonus: in the RQ sentence, report the relevant coefficient using APA formatting.

🗂️ See Resources > APA formatting for regression coefficients flash card.

Solution

Solution 9.

  • (Intercept):
    • For people with average anxiety, the grand mean heart rate is estimated to be 53.92 bpm.
  • strategyCloseEyes:
    • Holding anxiety constant, closing one’s eyes before the lie detector test is associated with an increase of 3.03 bpm compared to the grand mean bpm.
  • strategyCough:
    • Holding anxiety constant, coughing before the lie detector test is associated with a decrease of 0.84 bpm compared to the grand mean bpm.
  • anx:
    • Holding calming strategy constant, somebody with anxiety one SD above the mean is estimated to have a heart rate 3.40 bpm above the grand mean.

(Remember to mention the units too! You always want to write “[…] estimated to be 53.02 bpm”, not just “estimated to be 53.92.”)


To report a coefficient in APA format, we need to know its 95% CI.

confint(hr_mdl) |> round(2)
                  2.5 % 97.5 %
(Intercept)       52.94  54.89
strategyCloseEyes  1.49   4.57
strategyCough     -2.13   0.44
anx                1.93   4.87

The coefficient that’s relevant for the RQ is strategyCough, so we’ll focus on that one in this sentence which addresses the RQ:

When controlling for anxiety, coughing before a lie detector test is not significantly associated with a lower-than-average heart rate during the test (\(b\) = 0.84, 95% CI [–2.13, 0.44], \(p\) = .197).

Choosing coding schemes for different RQs

Question 10

This is a conceptual/interpretation question—no coding needed.

When you want to use a categorical predictor, you need to choose between treatment coding or sum coding. How do you choose? Based on which coding scheme will let you address your specific RQ best.

Here are five RQs. Based on the phrasing of each one, write down which contrast coding scheme you would use, and also explain why you chose that one. And if you choose treatment coding, also write down your choice of reference level.

  1. Do schoolchildren learn better when their classroom contains natural light compared to artificial light?
  2. What kind of background sound is associated with people spending more money in restaurants: no music, pop music, or classical music?
  3. Is life satisfaction in London lower than the average life satisfaction across UK cities?
  4. Do students in Psychology spend more time studying compared to the average study time across Philosophy, Psychology, and LEL?
  5. In a Stroop task, do neurotypical people perform worse than autistic people?

Solution

Solution 10. In general, if your RQ asks you to compare one level of a categorical variable with another level, you should use treatment coding. One of the levels involved in the comparison must be the reference level.

  • If the variable contains a “baseline” or “default” or “general” level, that should basically always be the reference level.
  • Otherwise, there’s no specific right answer.
  • I generally choose the reference level that will make the slope coefficient have the same sign (positive or negative) as the direction of the association in the research question. Examples in (1) and (5) below.

And if your RQ asks you to compare one level of a categorical variable with the average of that variable, then you want sum coding. Make sure that the level involved in the comparison is not your “dropped level”, the one coded as –1.


  1. Do schoolchildren learn better when their classroom contains natural light compared to artificial light?
  • The RQ asks about a direct comparison between two levels of a predictor, so we want treatment coding.
  • A good reference level: artificial light, so that the slope coefficient tells us how learning is different given natural light. (Either response is OK here though!)


  1. What kind of background sound is associated with people spending more money in restaurants: no music, pop music, or classical music?
  • The RQ asks about a direct comparison between two levels of a predictor, so we want treatment coding.
  • A good reference level: no music, because it’s a natural baseline to compare different kinds of music to.


    1. Is life satisfaction in London lower than the average life satisfaction across different UK cities?
  • The RQ asks about comparing a particular level (London) of a predictor to the average across all levels (all UK cities), so we want sum coding.


  1. Do students in Psychology spend more time studying compared to the average study time across Philosophy, Psychology, and LEL?
  • The RQ asks about comparing a particular level (Psychology) of a predictor to the average across all levels (all subject areas in PPLS), so we want sum coding.


  1. In a Stroop task, do neurotypical people perform worse than autistic people?
  • The RQ asks about a direct comparison between two levels of a predictor, so we want treatment coding.
  • A good reference level: autistic, so that the slope coefficient tells us how performance is different for neurotypical people. (Either response is OK here though!)

Optional: Knit your report to PDF

Note: During the labs, please spend your time on the exercises above, not on rendering your document. This guidance is here in case you have extra time at the end.

Rmarkdown is a useful format because it can be used as a foundation for generating different kinds of documents. For the group report, you’ll be asked to render your Rmd file to PDF. Why not practice now?

First, make sure you have tinytex installed in R. This is what lets you convert things into PDF format.

Run the following code to install tinytex (you’ll only need to run it once).

install.packages("tinytex")
tinytex::install_tinytex()

Then ensure that the “yaml” (rhymes with “mammal”) header—the bit at the top of your Rmd document—looks something like this:

---
title: "this is my report title"
author: "B1234506"
date: "07/09/2025"
output: bookdown::pdf_document2
---

Then follow the instructions from the Rmd bootcamp to knit your Rmd document to PDF.

If you encounter errors, refer to the DAPR1 formatting resources / knitting checklist.

TipWhat to do if you cannot knit to PDF

If you are having issues knitting directly to PDF, try the following:

  • Knit to HTML file
  • Open your HTML in a web-browser (e.g. Chrome, Firefox)
  • Print to PDF (Ctrl+P, then choose to save to PDF)
  • Open file to check formatting
TipHiding code and/or output from code chunks

Review Lesson 5 of the rmd bootcamp for a detailed description/worked examples.

Hiding R Code

To not show the code of an R code chunk, and only show the output, write:

```{r, echo=FALSE}
# code goes here
```

Hiding R Output:

To show the code of an R code chunk, but hide the output, write:

```{r, results='hide'}
# code goes here
```

Hiding R code AND output

To hide both code and output of an R code chunk, write:

```{r, include=FALSE}
# code goes here
```