-
Notifications
You must be signed in to change notification settings - Fork 8
/
time-varying-covariates.Rmd
62 lines (50 loc) · 2.21 KB
/
time-varying-covariates.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
---
title: "Time-varying covariates"
author: "Daniel Lüdecke"
date: "26 3 2019"
output: html_document
---
```{r setup, include=FALSE,echo=FALSE}
library(knitr)
knitr::opts_chunk$set(
echo = TRUE,
collapse = TRUE,
warning = FALSE,
comment = "#>",
dev = "png"
)
```
Time-varying covariates are most flexibly modelled with splines. Here are some examples, from simple longitudinal models to models with time-varying covariates.
* `y` = outcome (continuous / Gaussian)
* `t` = time-points
* `tv` = time-varying covariate
* `tc` = time-constant covariate
* `id` = subject-ID
```{r eval=FALSE}
# Model 1 - constant change in time
lmer(y ~ t + tv + tc + (1 + t | id), data)
# Model 2 - constant change in time, different slopes depending on covariate
# (interaction)
lmer(y ~ t * tv + tc + (1 + t | id), data)
# Model 3 - non-linear change in time
lmer(y ~ t + I(t^2) + tv + tc + (1 + t | id), data)
# Model 4 - non-linear change in time, different slopes depending on covariate
# (interaction)
lmer(y ~ t * tv + I(t^2) * tv + tc + (1 + t | id), data)
# Model 5 - non-linear change in time, time-varying covariate
# (interaction with non-linear covariate)
lmer(y ~ y ~ t * tv + I(t^2) * tv + t * I(tv^2) + I(t^2) * I(tv^2) + tc + (1 + t | id), data)
# Model 6 - non-linear change in time, time-varying covariate
# (cubic instead of quadratic interaction)
model6 <- lmer(
y ~ t * tv + I(t^2) * tv + I(t^3) * tv + t * I(tv^2) + t * I(tv^3) +
I(t^2) * I(tv^2) + I(t^2) * I(tv^3) + I(t^3) * I(tv^2) +
I(t^3) * I(tv^3) + tc + (1 + t | id),
data
)
```
This final model with splines is almost identical to model 6, when comparing marginal effects. The time-varying covariate needs to be specified in the `by`-argument from the spline-term. Time `t` is non-linear (spline), `tv` varies over time.
```{r eval=FALSE}
model7 <- lmer(y ~ s(t) + s(t, by = tv) + tc + (1 + t | id), data)
```
Note that for time-varying covariates, these may correlate with the group-level predictors. In such cases, a "complex random effects within-between" model is recommended, see https://strengejacke.github.io/mixed-models-snippets/random-effects-within-between-effects-model.html.