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) |
Interactions I: Num x Cat
Learning Objectives
At the end of this lab, you will:
- Understand the concept of an interaction
- Be able to interpret the meaning of a numeric \(\times\) categorical interaction
- Be able to visualize and probe interactions
What You Need
- Be up to date with lectures
- Have completed all labs from Semester 1
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
- kableExtra
- psych
- sjPlot
- patchwork
- sandwich
- interactions
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 association between wellbeing and the number of social interactions differ between rural and non-rural residents?
Setup
- Create a new RMarkdown file
- Load the required package(s)
- Read the wellbeing_rural dataset into R, assigning it to an object named
mwdata
Exercises
Study & Analysis Plan Overview
Provide a brief overview of the study design and data, before detailing your analysis plan to address the research question.
- State what type of analysis you will conduct in order to address the research question
- Specify the model to be fitted to address the research question (note that you will need to specify the reference level of your categorical variable)
- Specify your chosen significance (\(\alpha\)) level
- State your hypotheses
Much of the information required can be found in the Study Overview codebook.
If we fit the interaction x1:x2
, we almost always want to also fit the separate effects x1
and x2
:
“Except in special circumstances, a model including a product term for interaction between two explanatory variables should also include terms with each of the explanatory variables individually, even though their coefficients may not be significantly different from zero. Following this rule avoids the logical inconsistency of saying that the effect of \(X_1\) depends on the level of \(X_2\) but that there is no effect of \(X_1\).”
— Ramsey and Schafer (2012)
Check coding of variables (e.g., that categorical variables are coded as factors).
Note that the “location” variable currently has three levels (Rural/Suburb/City). In order to address the research question, we only want two (Rural/Not Rural) locations - you will need to fix this.
As specified in Q1, we want ‘not rural’ as the reference group, so make sure to specify this.
One way to do this would be to use ifelse()
to define a variable which takes one value (“Rural”) if the observation meets from some condition, or another value (“Not Rural”) if it does not.
Type ?ifelse
in the console if you want to see the help function. You can use it to add a new variable either inside mutate()
, or using data$new_variable_name <- ifelse(test, x, y)
syntax.
Descriptive Statistics & Visualisations
Provide a table of descriptive statistics and visualise your data.
In particular:
- Explore the associations among the variables included in your analysis
- Produce a visualisation of the association between weekly number of social interactions and well-being, with separate facets for rural vs non-rural respondents OR with different colours for each level of the
isRural
variable.
- For your table of descriptive statistics, both the
group_by()
andsummarise()
functions will come in handy here. - If you use the
select()
function and get an error along the lines ofError in select...unused arguments...
, you will need to specifydplyr::select()
(this just tells R which package to use the select function from). - The
pairs.panels()
function from thepsych
package can plot all variables in a dataset against one another. This will save you the time you would have spent creating individual plots, but is only useful for continuous variables.
- To include facets, within your
ggplot()
argument you will need to specify+ facet_wrap()
in order to produce facets for each location. It would also be useful to specifygeom_smooth(method="lm")
. - To include different colours for each location, you will need to specify
colour = isRural
within yourggplot()
argument, as well as+ scale_colour_discrete()
to state thename =
of your legend and thelabels =
associated with each coloured line.
Model Fitting & Interpretation
Fit your model using lm()
, and assign it as an object with the name “rural_mod”.
When fitting a regression model in R
with two explanatory variables A and B, and their interaction, these three are equivalent:
- y ~ A + B + A:B
- y ~ A + B + A*B
- y ~ A*B
Look at the parameter estimates from your model, and write a description of what each one corresponds to on the plot shown in Figure 1 (it may help to sketch out the plot yourself and annotate it, and refer to the drop down options below).
Recall that we can obtain our parameter estimates using various functions such as summary()
,coef()
, coefficients()
, etc.
No participants in our dataset had zero hours of social interactions per week (the lowest was 3), and we’re likely not interested in differences between rural and non-rural residents who have never interacted with others.
Mean center the continuous IV(s), and re-run your model with mean centered variable(s).
There are a couple of different ways that we can re-centre. We could either create a new variable, named say mc_social_int
which is social_int - mean(social_int)
(which would therefore make everyone who had 12.06 social interactions per week be given a value of 0
in the variable), or we could do it in the model:
Note any differences between the summary()
output between the original (“rural_mod”) and mean centred (“rural_mod1”) models. Pay particular attention to your coefficients and their significance values. How have your coefficients changed? Why do you think these differences have been observed?
These plots illustrate the difference between the “rural_mod” and “rural_mod1” models.
Visualise Interaction Model
Using the probe_interaction()
function from the interactions package, visualise the interaction effects from your model.
Try to summarise the interaction effects in a short and concise sentence.
In terms of specification, it might be useful to look up the helper function via ?probe_interaction
. As a quick guide:
-
model
= name model to be used -
pred
= The predictor variable -
modx
= The moderator variable -
interval
= If we sayTRUE
, then confidence/prediction intervals will be plotted around the line
Make sure to give your plot informative titles/labels. You, for example, likely want to give your plot:
- a clear and concise title (specify
main.title =
) - axis labels with units or scale included (specify
x.label =
andy.label =
) - a legend title (specify
legend.main =
)
Writing Up & Presenting Results
Provide key model results (from “rural_mod1”) in a formatted table.
Use tab_model()
from the sjPlot package.
You can rename your DV and IV labels by specifying dv.labels
and pred.labels
. To do so, specify your variable name on the left, and what you would like this to be named in the table on the right.
Interpret your results (from “rural_mod1”) in the context of the research question and report your model in full.
Make reference to the interaction plot and regression table.
“The best method of communicating findings about the presence of a significant interaction may be to present a table or graph of the estimated means at various combinations of the interacting variables.”
— Ramsey and Schafer (2012)
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
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()