This week (and every fifth week this year), you’ll practice writing up the analysis that was developed live during lectures.
Your goal is to present your analysis in a journal-article-style Results section that a reader could reproduce in any statistical software, not just R.
The example write-ups that will be provided are not perfect.
You must not copy them directly for this write-up or any future assessment, as copying and presenting them as your own work would constitute academic misconduct. But you may refer to them for stylistic guidance.
NoteGet set up
Open RStudio.
Create a new .Rmd file for this week’s exercises.
Save it somewhere you can find it again.
Give it a clear name (for example, dapr2_lab10.Rmd).
In the first code chunk, load the packages you’ll need this week (and install them if you don’t have them already):
tidyverse
psych
sjPlot
kableExtra
patchwork
car
broom.mixed
The data in UGattendance.csv contain six attributes collected from a simulated sample of \(n=326\) hypothetical individuals, and includes:
Variable
Description
pid
Participant ID number
Attendance
Total attendance (in days)
Conscientiousness
Conscientiousness (Levels: Low, Moderate, High)
Time
Time of Class (Levels: 9AM, 10AM, 11AM, 12PM, 1PM, 2PM, 3PM, 4PM)
OnlineAccess
Frequency of access to online course materials (Levels: Rarely, Sometimes, Often)
Year
Year of Study in University (Y1, Y2, Y3, Y4)
RQ: How are people’s conscientiousness and their year of undergraduate study associated with how often they attend their courses?
Predictions:
People with higher conscientiousness will attend their courses more than people with low conscientiousness.
People in further years of study will attend their courses less than people in first year.
TipProvided analysis code
This code should resemble the analysis developed during lectures this week.
# Categorical predictors: Practice analysis# Follows workflow here: dapr2/2627/dapr2_flashcards/resources/workflow-b2.html# Phase 1: Before model fitting ---- ## 1a: Set up code and data ---- # Load the required R packageslibrary(tidyverse)library(psych)library(sjPlot)library(kableExtra)library(patchwork)library(car)library(broom.mixed)# Read in dataattend_df <-read_csv("https://uoepsy.github.io/data/UGattendance.csv")# rename Conscientiousness because it's a lot to typeattend_df <- attend_df |>rename(Consc = Conscientiousness)# **Tidy data** (e.g., any missingness, any implausible values? are data types set correctly?).glimpse(attend_df) # some numeric, some continuous# - Check numeric for weird values using describe()attend_df |>select(pid, Attendance) |>describe() # min and max look reasonable# - Check each categorical for weird values using table()table(attend_df$Consc) # finetable(attend_df$Time) # finetable(attend_df$OnlineAccess) # finetable(attend_df$Year) # fine# - Check for NAstable(is.na(attend_df)) # no NAs, good to continue## 1b: Set up the variables you'll model ----# Based on the RQ, decide whether you'll test your hypotheses using coefficient significance tests or model comparison.# - RQ: How are people's conscientiousness and their year of undergraduate study associated with how often they attend their courses? # - This question is about associations between predictors and outcomes, so we can test it using coef significance tests.# Based on the RQ, identify your outcome variable and the predictors.# - Outcome: `Attendance`# - Predictors: `Consc` and `Year`# Set up categorical predictors (e.g., factor levels? which contrast coding scheme?)# - First, `Consc` has three levels: `Low`, `Moderate`, and `High`.# - This is not their alphabetical order, so let's specify this order using `mutate()`.attend_df <- attend_df |>mutate(Consc =factor(Consc, levels =c('Low', 'Moderate', 'High')) )# - We are interested in comparing people with higher conscientiousness to people with lower conscientiousness, so treatment coding is fine.# - How will `Consc` be coded?contrasts(attend_df$Consc)# - Reference level = `Low`, and two dummy variables which compare `Low` to `Moderate` and `Low` to `High`.# - Next, `Year` has many levels: Y1, Y2, Y3, Y4.# - We are comparing further years of study back to Y1, so we'll use Y1 as our reference level.# - Factor levels will end up in the right order, so we don't need to manually define them.attend_df <- attend_df |>mutate(Year =factor(Year) )contrasts(attend_df$Year)# - `Y1` is the ref level, and we have three dummy variables which compare Y1 to each following year.# Set up continuous predictors – NA.# Explore patterns in the data by plotting outcome and predictor variables together# - Consc:# boxplots are fine for a quick look, but not as good because it doesn't show the data itself# and also only shows the median, where what we want for linear modelling is the meanattend_df |>ggplot(aes(x = Consc, y = Attendance)) +geom_boxplot()# violin plots are better for a reportp_consc <- attend_df |>ggplot(aes(x = Consc, y = Attendance, fill = Consc, colour = Consc)) +geom_violin(alpha =0.5) +geom_jitter(height =0,height =0,alpha =0.5) +stat_summary(fun = mean, geom ='point', colour ='black', size =3) +theme(legend.position ='none')p_consc# - Year:# boxplot (quick and dirty)attend_df |>ggplot(aes(x = Year, y = Attendance)) +geom_boxplot()# violin plot (nicer)p_year <- attend_df |>ggplot(aes(x = Year, y = Attendance, fill = Year, colour = Year)) +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')p_year# - Patchwork the violin plots together for the report:p_consc + p_year# Phase 2: Model fitting ----# Write the mathematical model formulation for your model(s)# - Refer back to contrast matrices to know what the dummy variables will be.# $$# \text{Attendance} = \beta_0 + # (\beta_1 \cdot \text{Consc}_\text{Moderate}) + # (\beta_2 \cdot \text{Consc}_\text{High}) +# (\beta_3 \cdot \text{Year}_\text{Y2}) + # (\beta_4 \cdot \text{Year}_\text{Y3}) + # (\beta_5 \cdot \text{Year}_\text{Y4}) + # \epsilon# $$# - NOTE: Incorrect model formula (because disregards dummy variables):# $$# \text{Attendance} = \beta_0 + # (\beta_1 \cdot \text{Consc}) + # (\beta_2 \cdot \text{Year}) + # \epsilon# $$# Explicitly define the hypotheses that your RQ is aiming to test.# - Essentially we want to know whether there are significant associations # between any dummy variable and Attendance, so:# $$# \begin{align}# H_0 &: \text{ All } \beta_j = 0 \text{ for } j = 1, 2, 3, 4, 5\\# H_1 &: \text{ Any } \beta_j \neq 0\\# \end{align}# $$# Fit your model(s) using `lm()`.attend_mdl <-lm( Attendance ~ Consc + Year,data = attend_df)attend_mdl# Phase 3: After model fitting ----## 3a: Check assumptions and diagnostics ----# Check model assumptions:# - Linearity of association -- we can assume bc all preds are categorical# - Independence of errors -- we can assume bc we have one obs per ppt (pid column)# - Normality of errorsplot(attend_mdl, which =2) # good match to diagonal, sufficiently normal# - Equal variance of errorsplot(attend_mdl, which =1) # vertical spread varies a little. judgement call. I say sufficiently equal# - overall: looks fine!# Run diagnostics for multicollinearity.vif(attend_mdl)# - GVIF (categorical version) close to 1, so we're good!# Run diagnostics for influential observations.plot(attend_mdl, which =4)# - There are a few data points with relatively higher Cook's Distance values,# but none of them are twice as high as the next-highest, so we don't need to worry.# If you find extreme influential observations: run sensitivity analysis.# - NA## 3b: Plot and interpret model estimates ----# Interpret the coefficient estimatessummary(attend_mdl)confint(attend_mdl) |>round(2)# - `(Intercept)`# - The estimated mean attendance for people with low conscientiousness (Consc = 0 = Low) in first-year (Year = 0 = Y1) is 14.41 days.# # - `ConscModerate`# - Holding year of study constant, moving from low conscientiousness to moderate conscientiousness is associated with an estimated increase in attendance of 11.26 days.# # - `ConscHigh`# - Holding year of study constant, moving from low conscientiousness to high conscientiousness is associated with an estimated increase in attendance of 18.09 days.# # - `YearY2`# - Holding conscientiousness constant, moving from Y1 to Y2 is associated with an estimated increase in attendance of 4.78 days.# # - `YearY3`# - Holding conscientiousness constant, moving from Y1 to Y3 is associated with an estimated increase in attendance of 3.51 days.# # - `YearY4`# - Holding conscientiousness constant, moving from Y1 to Y4 is associated with an estimated increase in attendance of 4.63 days.# Generate a nicely-formatted regression table.tidy(attend_mdl) |>mutate(estimate =round(estimate, 2),std.error =round(std.error, 2),statistic =round(statistic, 2),p.value =ifelse(p.value < .001, '<.001', round(p.value, 3)) ) |>kable(booktabs =TRUE, caption ='Linear model coefficient estimates' )# Compare models and interpret model comparison statistics (if appropriate for your RQ) - NA.# Plot model-fitted values.plot_model( attend_mdl, type ='eff', terms =c('Year', 'Consc') # first term is the one on x axis) +labs(colour ='Conscientiousness' )## 3c: Write up -- in labs! ----
Question 1
Set the scene (so the reader knows what you’re talking about).
We want to find out how undergraduate students’ conscientiousness and year of study are associated with their attendance of university courses. We predict that people with higher conscientiousness will attend more than people with low conscientiousness, but that people in more advanced years of study will attend less than they did in their first year.
Question 2
Describe the sample data (so that the reader knows how generalisable your analysis might be).
We have data from 326 university students. For each student, we know the total number of days they have attended university, their level of conscientiousness (categorised into low, medium and high), and their year of study (Y1, Y2, Y3, Y4).
Question 3
Visualise and summarise data patterns that address the RQ (so the reader knows the basic pattern of what you found).
Tip: If you transform any continuous predictors for analysis, use the transformed version of the predictor in the plot.
Tip: In the caption, briefly explain what every geom in the plot represents. Especially error bars/shaded error ribbons! Always tell the reader what they show (standard deviation? standard error? 95% CI?).
Tip: Academic writing styles vary, but Elizabeth likes it when figure captions give the reader a brief take-home message about what they should see in the plot.
Tip: No inferential stats have been done yet, so we can’t make any claims just yet about whether the predictions were supported. But it is OK to say whether the results appear broadly in line with the prediction.
Students’ attendance is visualised alongside their conscientiousness level and year of study in Figure 1. It appears that, as conscientiousness levels increase, attendance improves, and as year of study increases, attendance also tends to improve (with some variability).
Figure 1: Relationships between conscientiousness, year of study, and days of attendance. Each student’s data is represented by one coloured dot, and black dots represent the mean attendance for each group. Generally speaking, higher conscientiousness and more advanced years of study appear to co-occur with higher attendance.
Question 4
Introduce your statistical analysis (so the reader can interpret the numbers you will report).
Tip: If you’ll report your results using the full regression table for your coefficients, then also include the full regression table for the sensitivity analysis in another Appendix section.
We conducted all statistical analyses using R (R Core Team, 2026), and we will consider effects significant at \(\alpha = .05\).
To address our research question, we fit a linear model predicting attendance (in days) as a function of conscientiousness level and year of study. Conscientiousness was treatment-coded, with “Low” as the reference level (resulting in two dummy variables), and year of study was treatment-coded as well, with “Y1” as the reference level (resulting in three dummy variables). The mathematical model formulation is as follows.
\[
\begin{align}
\text{Attendance } =& \beta_0 +
(\beta_1 \cdot \text{Consc}_\text{Moderate}) +
(\beta_2 \cdot \text{Consc}_\text{High}) ~ + \\
& (\beta_3 \cdot \text{Year}_\text{Y2}) +
(\beta_4 \cdot \text{Year}_\text{Y3}) +
(\beta_5 \cdot \text{Year}_\text{Y4}) + \epsilon \\
\end{align}
\] We are testing the null hypothesis that all slope coefficients are equal to zero, that is, that there is no association between any predictor and attendance. Formally:
\[
\begin{align}
H_0 &: \text{ All } \beta_j = 0 \text{ for } j = 1, 2, 3, 4, 5\\
H_1 &: \text{ Any } \beta_j \neq 0\\
\end{align}
\]
After fitting this model, we checked the assumptions we must make about the model and the data. First, we can readily assume that associations are linear, because all predictors are categorical. Second, we can also assume that all data points are independent, because each observation comes from a different student. Third, errors appear sufficiently normally-distributed (see Figure A.1 in Appendix A), and fourth, errors also have sufficiently equal variance (see Figure A.2 in Appendix A).
We also checked for multicollinearity between the two predictors. Both GVIF values are close to 1, indicating little variance inflation, so multicollinearity is not a concern for this analysis.
Finally, we checked for influential data points and found none with extreme Cook’s Distance values compared to the others (see Figure A.3 in Appendix A). So we now turn to interpreting our model’s estimates.
Question 5
Report the results of your analysis (so the reader knows exactly what you found).
Tip: You don’t need to report every single parameter estimate. Focus on the one(s) you identified as being relevant to your prediction(s).
Tip: Briefly link the direction and significance of the effect back to your earlier predictions—is the prediction supported by the parameter estimate?
Tip: if you DO report all coefficient estimates in the text, then there’s no need to include the coefficient table because the information is redundant.
Focusing first on conscientiousness: if attendance increases as conscientiousness increases, then we would expect the coefficient that compares moderate to low conscientiousness to be positive and the coefficient that compares high to low conscientiousness to be even more positive. That is what we find. Holding year of study constant, somebody with moderate conscientiousness is estimated to attend 11.26 more days, on average, than someone with low conscientiousness (\(b\) = 11.26, 95% CI [8.18, 14.34], \(p\) < .001). And someone with high conscientiousness is estimated to attend 18.09 more days (\(b\) = 18.09, 95% CI [14.86, 21.32], \(p\) < .001).
Turning now to year of study: if attendance decreases as year of study increases, we would expect negative coefficients which get ever more negative for continuing years of study. This prediction is not supported. In fact, in general, the opposite pattern tends to hold, with attendance tending to increase as years of study go on. Y2 and Y4 have significantly greater attendance than Y1, while Y3 does not differ significantly from Y1. See Table 1 for a summary of regression coefficients. Model-fitted attendance estimates for all combinations of conscientiousness and year of study are visualised in Figure 2.
To summarise, we found that students’ conscientiousness and year of study are indeed associated with their attendance, and we can reject the H0 set up above. More specifically, our prediction about conscientiousness was supported: holding year of study constant, students with higher conscientiousness attend more often. But our prediction about year of study was not supported. Holding conscientiousness constant, attendance actually tends to increase from Y1 onward—the opposite of what we expected.
Code
tidy(attend_mdl) |>mutate(estimate =round(estimate, 2),std.error =round(std.error, 2),statistic =round(statistic, 2),p.value =ifelse(p.value < .001, '<.001', round(p.value, 3)) ) |># this next bit gives the columns nicer-looking namesrename(Term = term,Estimate = estimate,SE = std.error,`t-value`= statistic,`p-value`= p.value ) |># # this next bit tidies up what's displayed in the "Term" columnmutate(Term =case_when(# in general, the syntax here is:# Term == '<current coef name>' ~ '<the nice name you want to show>' Term =='(Intercept)'~'Intercept (Low Consc, Year 1)', Term =='ConscModerate'~'Consc (Moderate)', Term =='ConscHigh'~'Consc (High)', Term =='YearY2'~'Year (Y2)', Term =='YearY3'~'Year (Y3)', Term =='YearY4'~'Year (Y4)' ) ) |>kable(booktabs =TRUE, caption ='Table 1: Linear model coefficient estimates' )
Table 1: Linear model coefficient estimates
Term
Estimate
SE
t-value
p-value
Intercept (Low Consc, Year 1)
14.42
1.56
9.21
<.001
Consc (Moderate)
11.26
1.57
7.19
<.001
Consc (High)
18.09
1.64
11.02
<.001
Year (Y2)
4.78
1.71
2.80
0.005
Year (Y3)
3.51
1.91
1.84
0.067
Year (Y4)
4.63
1.86
2.49
0.013
Code
plot_model( attend_mdl, type ='eff', terms =c('Year', 'Consc') # first term is the one on x axis) +labs(colour ='Conscientiousness' )
Figure 2: Model-fitted values for attendance across years of study and levels of conscientiousness, showing a generally increasing pattern over years and for increasing conscientiousness. Points represent the estimates and error bars represent their 95% CIs.
Question 6
Appendices might include:
Appendix A: Assumption and diagnostic checks
Code
plot(attend_mdl, which =2)
Figure A.1: In a Q-Q plot, normally-distributed errors should follow the dashed diagonal line. The residuals of our model appear sufficiently normally distributed.
Code
plot(attend_mdl, which =1)
Figure A.2: In a residuals vs. fitted plot, errors with equal variance should be evenly vertically distributed across the whole range of the fitted values on the x axis. Our model’s residuals may show some small deviations from equal variance (e.g., slightly less variability for large fitted values), but we consider the variance equal enough.
Code
plot(attend_mdl, which =4)
Figure A.3: None of the most influential observations has a Cook’s Distance that’s more than twice as large as the next-largest one.
We want to find out how undergraduate students’ conscientiousness and year of study are associated with their attendance of university courses. We predicted that people with higher conscientiousness will attend more than people with low conscientiousness, but that people in more advanced years of study will attend less than they did in their first year.
We have data from 326 university students. For each student, we know the total number of days they have attended university, their level of conscientiousness (categorised into low, medium and high), and their year of study (Y1, Y2, Y3, Y4).
Students’ attendance is visualised alongside their conscientiousness level and year of study in Figure 1. It appears that, as conscientiousness levels increase, attendance improves, and as year of study increases, attendance also tends to improve (with some variability).
Figure 1: Relationships between conscientiousness, year of study, and days of attendance. Each student’s data is represented by one coloured dot, and black dots represent the mean attendance for each group. Generally speaking, higher conscientiousness and more advanced years of study appear to co-occur with higher attendance.
We conducted all statistical analyses using R (R Core Team, 2026), and we will consider effects significant at \(\alpha = .05\).
To address our research question, we fit a linear model predicting attendance (in days) as a function of conscientiousness level and year of study. Conscientiousness was treatment-coded, with “Low” as the reference level (resulting in two dummy variables), and year of study was treatment-coded as well, with “Y1” as the reference level (resulting in three dummy variables). The mathematical model formulation is as follows.
\[
\begin{align}
\text{Attendance } =& \beta_0 +
(\beta_1 \cdot \text{Consc}_\text{Moderate}) +
(\beta_2 \cdot \text{Consc}_\text{High}) ~ + \\
& (\beta_3 \cdot \text{Year}_\text{Y2}) +
(\beta_4 \cdot \text{Year}_\text{Y3}) +
(\beta_5 \cdot \text{Year}_\text{Y4}) + \epsilon \\
\end{align}
\] We are testing the null hypothesis that all slope coefficients are equal to zero, that is, that there is no association between any predictor and attendance. Formally:
\[
\begin{align}
H_0 &: \text{ All } \beta_j = 0 \text{ for } j = 1, 2, 3, 4, 5\\
H_1 &: \text{ Any } \beta_j \neq 0\\
\end{align}
\]
After fitting this model, we checked the assumptions we must make about the model and the data. First, we can readily assume that associations are linear, because all predictors are categorical. Second, we can also assume that all data points are independent, because each observation comes from a different student. Third, errors appear sufficiently normally-distributed (see Figure B.1 in Appendix A), and fourth, errors also have sufficiently equal variance (see Figure B.2 in Appendix A).
We also checked for multicollinearity between the two predictors. Both GVIF values are close to 1, indicating little variance inflation, so multicollinearity is not a concern for this analysis.
Finally, we checked for influential data points and found none with extreme Cook’s Distance values compared to the others (see Figure A.3 in Appendix A). So we now turn to interpreting our model’s estimates.
Focusing first on conscientiousness: if attendance increases as conscientiousness increases, then we would expect the coefficient that compares moderate to low conscientiousness to be positive and the coefficient that compares high to low conscientiousness to be even more positive. That is what we find. Holding year of study constant, somebody with moderate conscientiousness is estimated to attend 11.26 more days, on average, than someone with low conscientiousness (\(b\) = 11.26, 95% CI [8.18, 14.34], \(p\) < .001). And someone with high conscientiousness is estimated to attend 18.09 more days (\(b\) = 18.09, 95% CI [14.86, 21.32], \(p\) < .001).
Turning now to year of study: if attendance decreases as year of study increases, we would expect negative coefficients which get ever more negative for continuing years of study. This prediction is not supported. In fact, in general, the opposite pattern tends to hold, with attendance tending to increase as years of study go on. Y2 and Y4 have significantly greater attendance than Y1, while Y3 does not differ significantly from Y1. See Table 1 for a summary of regression coefficients. Model-fitted attendance estimates for all combinations of conscientiousness and year of study are visualised in Figure 2.
Table 1: Linear model coefficient estimates
Term
Estimate
SE
t-value
p-value
Intercept (Low Consc, Year 1)
14.42
1.56
9.21
<.001
Consc (Moderate)
11.26
1.57
7.19
<.001
Consc (High)
18.09
1.64
11.02
<.001
Year (Y2)
4.78
1.71
2.80
0.005
Year (Y3)
3.51
1.91
1.84
0.067
Year (Y4)
4.63
1.86
2.49
0.013
Figure 2: Model-fitted values for attendance across years of study and levels of conscientiousness, showing a generally increasing pattern over years and for increasing conscientiousness. Points represent the estimates and error bars represent their 95% CIs.
To summarise, we found that students’ conscientiousness and year of study are indeed associated with their attendance, and we can reject the H0 set up above. More specifically, our prediction about conscientiousness was supported: holding year of study constant, students with higher conscientiousness attend more often. But our prediction about year of study was not supported. Holding conscientiousness constant, attendance actually tends to increase from Y1 onward—the opposite of what we expected.
Appendix A: Assumption and diagnostic checks
Code
plot(attend_mdl, which =2)
Figure A.1: In a Q-Q plot, normally-distributed errors should follow the dashed diagonal line. The residuals of our model appear sufficiently normally distributed.
Code
plot(attend_mdl, which =1)
Figure A.2: In a residuals vs. fitted plot, errors with equal variance should be evenly vertically distributed across the whole range of the fitted values on the x axis. Our model’s residuals may show some small deviations from equal variance (e.g., slightly less variability for large fitted values), but we consider the variance equal enough.
Code
plot(attend_mdl, which =4)
Figure A.3: None of the most influential observations has a Cook’s Distance that’s more than twice as large as the next-largest one.
References
R Core Team (2026). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. https://www.R-project.org/.
Optional: Knit your report to PDF
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).