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 well-being. 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) |
Simple Linear Regression
Learning Objectives
At the end of this lab, you will:
- Be able to specify a simple linear model
- Understand what fitted values and residuals are
- Be able to interpret the coefficients of a fitted model
Requirements
- Be up to date with lectures
- Have watched course intro video in Week 0 folder, and completed associated tasks
Required R Packages
Remember to load all packages within a code chunk at the start of your RMarkdown file using library()
. If you do not have a package and need to install, do so within the console using install.packages(" ")
. For further guidance on installing/updating packages, see Section C here.
For this lab, you will need to load the following package(s):
- tidyverse
- sjPlot
- kableExtra
Presenting Results
All results should be presented following APA guidelines.If you need a reminder on how to hide code, format tables/plots, etc., make sure to review the rmd bootcamp.
The example write-up sections included as part of the solutions are not perfect - they instead should give you a good example of what information you should include and how to structure this. Note that you must not copy any of the write-ups included below for future reports - if you do, you will be committing plagiarism, and this type of academic misconduct is taken very seriously by the University. You can find out more here.
Lab Data
You can download the data required for this lab here or read it in via this link https://uoepsy.github.io/data/wellbeing_rural.csv
Study Overview
Research Question
Does the number of weekly social interactions influence wellbeing scores?
Setup
- Create a new RMarkdown file
- Load the required package(s)
- Read the wellbeing dataset into R, assigning it to an object named
mwdata
Exercises
Marginal Distributions
Visualise and describe the marginal distributions of wellbeing scores and social interactions.
Review the many ways to numerically and visually explore your data by reading over the data exploration flashcards.
For examples of mariginal distrubtion visualisation examples, see the data visualisation - marginal examples flashcards.
Associations among Variables
Create a scatterplot of wellbeing score and social interactions before calculating the correlation between them.
Making reference to both the plot and correlation coefficient, describe the association between wellbeing and social interactions among participants in the Edinburgh & Lothians sample.
Review the many ways to numerically and visually explore your data by reading over the data exploration flashcards.
Model Specification and Fitting
The scatterplot highlighted a linear association, where the data points were scattered around an underlying linear pattern with a roughly-constant spread as x varied.
Hence, we will try to fit a simple (i.e., one x variable only) linear regression model:
\[ y_i = \beta_0 + \beta_1 x_i + \epsilon_i \\ \quad \text{where} \quad \epsilon_i \sim N(0, \sigma) \text{ independently} \]
First, write the equation of the fitted line.
Next, using the lm()
function, fit a simple linear model to predict wellbeing (DV) by social interactions (IV), naming the output mdl
.
Lastly, update your equation of the fitted line to include the estimated coefficients.
See the statistical models flashcards for a reminder on how to specify models.
For how to format and write your model in RMarkdown, see the LaTeX symbols and equations flashcard.
Explore the following equivalent ways to obtain the estimated regression coefficients — that is, \(\hat \beta_0\) and \(\hat \beta_1\) — from the fitted model:
mdl
mdl$coefficients
coef(mdl)
coefficients(mdl)
summary(mdl)
Explore the following equivalent ways to obtain the estimated standard deviation of the errors — that is, \(\hat \sigma\) — from the fitted model mdl
:
sigma(mdl)
summary(mdl)
Interpret the estimated intercept, slope, and standard deviation of the errors in the context of the research question.
To interpret the estimated standard deviation of the errors we can use the fact that about 95% of values from a normal distribution fall within two standard deviations of the center.
Plot the data and the fitted regression line. To do so:
- Extract the estimated regression coefficients e.g., via
betas <- coef(mdl)
- Extract the first entry of
betas
(i.e., the intercept) viabetas[1]
- Extract the second entry of
betas
(i.e., the slope) viabetas[2]
- Provide the intercept and slope to the function
Extracting values
The function coef(mdl)
returns a vector (a sequence of numbers all of the same type). To get the first element of the sequence you append [1]
, and [2]
for the second.
Plotting
In your ggplot()
, you will need to specify geom_abline()
. This might help get you started:
geom_abline(intercept = intercept, slope = slope)
For further ggplot()
guidance, see the how to visualise data flashcard.
Predicted Values & Residuals
Use predict(mdl)
to compute the fitted values and residuals. Mutate the mwdata
dataframe to include the fitted values and residuals as extra columns.
Assign to the following symbols the corresponding numerical values:
- \(y_{3}\) (response variable for unit \(i = 3\) in the sample data)
- \(\hat y_{3}\) (fitted value for the third unit)
- \(\hat \epsilon_{5}\) (the residual corresponding to the 5th unit, i.e., \(y_{5} - \hat y_{5}\))
For a more detailed description and worked example, check the model predicted values & residuals flashcards.
Writing Up & Presenting Results
Provide key model results in a formatted table.
Use tab_model()
from the sjPlot package. For a quick guide, review the tables flashcard.
Describe the design of the study (see Study Overview codebook), and the analyses that you undertook. Interpret your results in the context of the research question and report your model results in full.
Make reference to your descriptive plots and/or statistics and regression table.
Compile Report
Knit your report to PDF, and check over your work. To do so, you should make sure:
- Only the output you want your reader to see is visible (e.g., do you want to hide your code?)
- Check that the tinytex package is installed
- Ensure that the ‘yaml’ (bit at the very top of your document) looks something like this:
---
title: "this is my report title"
author: "B1234506"
date: "07/09/2024"
output: bookdown::pdf_document2
---
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
Review Lesson 5 of the rmd bootcamp for a detailed description/worked examples.
To not show the code of an R code chunk, and only show the output, write:
```{r, echo=FALSE}
# code goes here
```
To show the code of an R code chunk, but hide the output, write:
```{r, results='hide'}
# code goes here
```
To hide both code and output of an R code chunk, write:
```{r, include=FALSE}
# code goes here
```
You must make sure you have tinytex installed in R so that you can “Knit” your Rmd document to a PDF file:
install.packages("tinytex")
tinytex::install_tinytex()