# How to construct a general linear model with repeated measures and covariate

I’m trying to make a general linear model to examine differences in weight between three diets (diet1, diet2, diet3) while accounting for a covariate (bloodpressure). I have a sample of 30 individuals. Each individual completes diet1, diet2, and diet 3, and their weight is measured after each diet.

Here is some sample data:

dat <- tibble::tibble(pid = as.factor(rep(1:30, 3)), weight = c(rnorm(30, 151, 10), rnorm(30, 150, 11), rnorm(30, 170, 9)), bloodpressure = c(rnorm(30, 70, 7), rnorm(30, 80, 8.5), rnorm(30, 91, 9.8)), diet = as.factor(c(rep("diet1", 30), rep("diet2", 30), rep("diet3", 30))))

Would I be on the right track with the following calls?:

fit <- lm(weight ~ diet + bloodpressure + pid, data = dat)
posthoc <- emmeans::emmeans(fit, "diet")
pairs(posthoc)


My thinking is that adding “pid” into lm() will capture the repeated measures aspect of the data but I’m not sure if this is correct...

Alternatively, would this be a better model? Or am I completely going about this the wrong way?

fit2 <- aov(weight ~ diet + bloodpressure + Error(pid), data = dat)
%>% summary


Thanks for any help & clarification!

• Both are reasonable. fit models subjects as a fixed effect, while fit2 treats them as random. Since you pipe that to summary(), does fit2 save the model or its summary? There are some technical issues with aov() if the design is unbalanced, and you should fit it after setting options(contrasts = c("contr.sum", "contr.poly")). Often these days, people would use library(lme4) and fit3 <- lmer(weight~diet + bloodpressure + (1|pid), data = dat) Jun 1, 2021 at 20:44
• @RussLenth - Thanks so much for the helpful reply. I think a mixed models approach would be the best way to move forward after looking more into the lme4 documentation. The line that you provide is an especially useful bit, and is very much appreciated!! Jun 2, 2021 at 18:03