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
    • 09: Bootstrapping
    • 10: Practice write-up
  • Block 3: Interactions
  • Block 4: Logistic regression

On this page

  • Set up data and model
  • Bootstrap
  • Develop study materials/strategies
  • Optional: Knit your report to PDF

09: Bootstrapping

This week, you’ll bootstrap some coefficient estimates for last week’s model.

There’s relatively little new coding this week, so if you have extra time after running through the exercises, why not start putting together some study materials? Your future self will thank you :) We give some recommendations in Q6 below.

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_lab09.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
    • car

Research question (RQ): Is there an association between wellbeing and time spent outdoors, when controlling for the effect that social interaction has on wellbeing?

Data dictionary:

variable description
age Age in years of respondent
outdoor_time Self report estimated number of hours per week spent outdoors
social_int Self report estimated number of social interactions per week (both online and in-person)
routine Binary 1=Yes/0=No response to the question 'Do you follow a daily routine throughout the week?'
wellbeing Warwick-Edinburgh Mental Wellbeing Scale (WEMWBS), a self-report measure of mental health and wellbeing. The scale is scored by summing responses to each item, with items answered on a 1 to 5 Likert scale. The minimum scale score is 14 and the maximum is 70
location Location of primary residence (City, Suburb, Rural)
steps_k Average weekly number of steps in thousands (as given by activity tracker if available)
NoteMore detail about this dataset

From the Edinburgh & Lothians, 100 city/suburb residences and 100 rural residences were chosen at random and contacted to participate in the study. The Warwick-Edinburgh Mental Wellbeing Scale (WEMWBS) was used to measure mental health and wellbeing.

Participants filled out a questionnaire including items concerning: estimated average number of hours spent outdoors each week, estimated average number of social interactions each week (whether on-line or in-person), whether a daily routine is followed (yes/no). For those respondents who had an activity tracker app or smart watch, they were asked to provide their average weekly number of steps.

Set up data and model

Question 1

We recommend that you copy and paste code that you wrote last week in Lab 08 for this question.

Read in the data from https://uoepsy.github.io/data/wellbeing_rural.csv and store it in a variable named mwdata (“mw” stands for “mental wellbeing”).

Fit the linear model represented by the mathematical model formulation below and (unlike Lab 03!) name the result m1.

\[ \text{wellbeing} = \beta_0 + (\beta_1 \cdot \text{outdoor\_time}) + (\beta_2 \cdot \text{social\_int}) + \epsilon \]

Solution

Solution 1.

mwdata <- read_csv("https://uoepsy.github.io/data/wellbeing_rural.csv")
m1     <- lm(wellbeing ~ outdoor_time + social_int, data = mwdata)

Question 2

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

Here’s a plot from last week’s lab that illustrates a problem with this model’s residuals:

plot(m1, which = 1)

From memory, do your best to write down:

  1. what assumption this plot is checking,
  2. what each point represents, and
  3. what the problem is with the data in this plot.

After you’ve made a good-faith effort to respond to each point from memory, you can revisit last week’s lab/notes/flash cards to complete your responses.

Solution

Solution 2.

  1. This is a residuals-vs-fitted plot, and it’s used to visually assess the assumption of equal variance of errors.

  2. Each point represents one observation from our dataset: specifically, its residual (y axis) and its model-fitted/model-predicted outcome value (x axis).

  3. The problem is that these data points appear to build a fan/funnel/cone shape, where the vertical spread is much smaller at one end of the x axis compared to the other. This pattern indicates unequal variance, and it means we can’t totally trust the model’s estimates of variability, because they won’t apply equally to the whole dataset, and we also can’t totally trust the model’s predicted outcome values, because they’ll be much more accurate when they are small (toward the left side of the plot) and much less accurate when they are large (toward the right side of the plot).

Bootstrap

Question 3

One way to get around the suspicious residuals in the plot above is to bootstrap our linear model’s estimates.

Quick explanation: Why does bootstrapping work? By bootstrapping the model—that is, by fitting the model on a different subset of our data each time—we will end up with a distribution of sampled values for each model coefficient. The mean of that distribution is our coefficient estimate, and the standard deviation of that distribution is our coefficient’s standard error.

Thus bootstrapping gives us a different way to calculate the standard error of our observation, a way that doesn’t rely on the model’s own variability estimates. This is good, because we want to avoid the model’s variability estimates. Why? Because, as the plot above shows, they are not equal across the whole range of the fitted values, so any model-based estimates aren’t going to be entirely trustworthy.

So: using the function Boot(), bootstrap 1000 samples based on the model m1. Name the output m1_boot.

TipCode hint

Replace the ... in the code below with the appropriate values.

... <- Boot(..., R = ...)

🗂️ See Bootstrapping flash card.

Solution

Solution 3.

m1_boot <- Boot(m1, R = 1000)

Question 4

Copy and run the following line of code.

summary(m1_boot)

Write down for yourself:

  1. Which column of the output represents the coefficent estimate?
  2. Which the column of the output represents the standard error (i.e., the standard deviation of the sampling distribution)?

🗂️ See Bootstrapping flash card.

Solution

Solution 4.

summary(m1_boot)

Number of bootstrap replications R = 1000 
             original    bootBias   bootSE  bootMed
(Intercept)  28.62018  0.01189038 1.458550 28.73762
outdoor_time  0.19909 -0.00043244 0.051237  0.19708
social_int    0.33488 -0.00080506 0.093194  0.32830
  1. original is the column containing the coefficient estimate.

  2. bootSE is the column containing the bootstrapped standard error.

Question 5

Using the function confint(), find the 95% CIs for each coefficient estimate.

Write down: Can we reject the H0 (at \(\alpha\) = .05) that each coefficient is equal to zero?

🗂️ See Bootstrapping flash card.

Solution

Solution 5.

confint(m1_boot)
Bootstrap bca confidence intervals

                  2.5 %     97.5 %
(Intercept)  25.2619558 31.0537501
outdoor_time  0.1037972  0.3043128
social_int    0.1700998  0.5504829

None of these 95% CIs contain zero, so for all three coefficients, we can reject the H0 at \(\alpha\) = .05.

Develop study materials/strategies

Question 6

If you reach this point and still have a bit of time to dedicate to DAPR this week, we’d recommend that you start thinking about study/revision materials and strategies.

It’s true that report and exam season is still far away, but it’s good to start these things early. Your learning will develop best through little bits of continuous effort. So the more prep you do now, the more your understanding will grow over time.

Here are some of Elizabeth’s favourite learning strategies (note that it’s the process here that will help you learn, much more than just getting an end product):

  1. Mind mapping: Create visual representations of how concepts are connected. You could start a mind map now and keep updating it as the course goes on.
  2. Flash cards (and other active recall methods): Testing yourself using active recall now will train your brain in retrieving key information, so that it’s there when you need it later.
    • If you like using physical flash cards, try the Leitner system, a system that adds in spaced repetition to help build your long-term memory.
  3. The Feynman technique: Teach or explain an idea as simply as you can. Wherever you’re not sure what to say or how to explain something, brush up on those areas and try again.
    • Artemis adds that you can also do this explanation method in groups, if you want to mix solo and group study! For example, you might each prep individually and then get together to explain key concepts to one another.
    • If you don’t know where to start, here are some important questions that you could try to develop an explanation for (again, it’s your process of developing the explanation that’s key, not the actual explanation):
      • For any intercept in any model, what’s the most general way to describe what it means?
      • For any slope in any simple regression model (that is, a model with one predictor), what’s the most general way to describe what it means?
      • For any slope in any multiple regression model (that is, a model with two or more predictors), what’s the most general way to describe what it means?
      • Why is it important to know what the value zero represents for any predictor?
      • What is the basic reasoning process / logic of null hypothesis significance testing?

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
```