This article works through one analysis from start to end: the model, the data, specifying and fitting a model, reading the results, adding a covariate and checking the model. It assumes ctsem and its Julia engine are installed, as the README describes.
The model
A ctsem model describes one or more latent processes that change over time, and the variables measured at the times they were observed. Within each subject the processes follow
and the measurements are
Each symbol is a matrix of ctModel():
| Matrix | Symbol | Holds | Default |
|---|---|---|---|
DRIFT |
auto effects (diagonal) and cross effects between processes | free | |
CINT |
continuous time intercepts | zero | |
DIFFUSION |
size and correlation of the random shocks to the processes | free | |
TDPREDEFFECT |
effects of time dependent predictors | free | |
T0MEANS |
the processesโ values at each subjectโs first observation | free, varying over subjects | |
T0VAR |
their variance at the first observation | covered by the random T0MEANS
|
|
LAMBDA |
loadings of the measured variables on the processes | must be given | |
MANIFESTMEANS |
intercepts of the measured variables | free, varying over subjects | |
MANIFESTVAR |
measurement error | free standard deviations |
The drift matrix describes how the processes change. With a negative
auto effect, a process on its own returns towards its equilibrium after
a shock. A cross effect is the effect of one process on the rate of
change of another. Whether the processes together return to equilibrium
depends on the whole drift matrix, which
vignette('dynamics') explains. The diffusion describes the
random shocks that move the processes between observations, and so carry
forward in time. Measurement error affects only the observation it
belongs to. A time dependent predictor, such as an intervention, shifts
the processes at the times it is observed, and the dynamics carry the
shift forward.
Any parameter can differ between subjects, as a random effect, and depend on subject level covariates (time independent predictors). By default the initial states and the intercepts of the measured variables differ between subjects, which allows for stable differences between people.
With type = 'dt' the same matrices describe a discrete
time model, in which DRIFT holds the autoregressive and
cross-lagged coefficients from one occasion to the next.
Data
ctsem takes data in long format: one row per subject and occasion, with a column for the subject id, one for the time, and one for each measured variable and predictor.
- Times are numbers, in whatever unit suits the processes, such as hours, days or years. They need not be equally spaced and can differ between subjects. The estimated effects are per unit of time, so the unit decides their scale. A unit over which the processes change noticeably, but do not settle completely, usually works best.
- A missing value is
NA. A row can have some variables observed and others missing. - A time independent predictor must have the same value on every row of a subject.
- A time dependent predictor is an input at the time of its row, and zero means no input.
The data for this article are simulated, so that the estimates can be
compared with the values that generated them. One hundred people rated
their stress and mood about once a day, at irregular times, for a month
or so, and some ratings are missing. In the generating model stress
lowers mood but mood does not affect stress, each person has their own
typical stress and mood, and older people tend to be more stressed.
age is standardised.
set.seed(1)
gen <- ctModel(type = 'ct', silent = TRUE,
manifestNames = c('stress', 'mood'), latentNames = c('stress', 'mood'),
LAMBDA = diag(2), TIpredNames = 'age',
DRIFT = matrix(c(-0.5, 0, -0.25, -0.3), 2, 2, byrow = TRUE),
DIFFUSION = matrix(c(0.8, 0, 0, 0.6), 2, 2, byrow = TRUE),
CINT = matrix(0, 2, 1), T0MEANS = matrix(0, 2, 1), T0VAR = diag(1, 2),
MANIFESTMEANS = matrix(c('mm_stress|param|TRUE|0.5|age=0.3',
'mm_mood|param|TRUE|0.5'), 2, 1),
MANIFESTVAR = diag(0.4, 2))
dat <- ctGenerate(gen, n = 100, Tpoints = 30, dtmean = 1, logdtsd = 0.5,
backend = 'julia', values = c(mm_stress = 3, mm_mood = 5))
truelevels <- attr(dat, 'subjectpars')
dat <- data.frame(dat)
dat$time <- round(dat$time, 2)
dat$stress[sample(nrow(dat), 200)] <- NA
dat$mood[sample(nrow(dat), 200)] <- NA
head(dat)
#> id time stress mood age
#> 1 1 0.00 2.700413 4.601892 0.7391149
#> 2 1 0.73 3.065700 NA 0.7391149
#> 3 1 1.83 2.319692 4.910601 0.7391149
#> 4 1 2.49 NA 6.159872 0.7391149
#> 5 1 4.71 4.396647 3.978655 0.7391149
#> 6 1 5.89 3.555298 5.576969 0.7391149
long <- rbind(
data.frame(dat[dat$id <= 3, c('id', 'time')], variable = 'stress',
value = dat$stress[dat$id <= 3]),
data.frame(dat[dat$id <= 3, c('id', 'time')], variable = 'mood',
value = dat$mood[dat$id <= 3]))
ggplot(long[!is.na(long$value), ], aes(time, value, colour = variable)) +
geom_line() + geom_point(size = 1) + facet_wrap(~id, labeller = label_both) +
theme_bw() + labs(x = 'time (days)', y = NULL)
Data in wide format, with one row per subject, can be converted.
ctWideToLong() gives one row per occasion, and
ctDeintervalise() turns the time intervals of wide data
into times:
data(ctExample1)
colnames(ctExample1)
#> [1] "LeisureTime_T0" "Happiness_T0" "LeisureTime_T1" "Happiness_T1"
#> [5] "LeisureTime_T2" "Happiness_T2" "LeisureTime_T3" "Happiness_T3"
#> [9] "LeisureTime_T4" "Happiness_T4" "LeisureTime_T5" "Happiness_T5"
#> [13] "dT1" "dT2" "dT3" "dT4"
#> [17] "dT5"
widelong <- ctWideToLong(ctExample1, Tpoints = 6, n.manifest = 2,
manifestNames = c('LeisureTime', 'Happiness'))
widelong <- data.frame(ctDeintervalise(widelong))
head(widelong)
#> id time LeisureTime Happiness
#> 1 1 0 3.810624 11.15498
#> 2 1 1 3.501790 10.23646
#> 3 1 3 3.860780 12.26379
#> 4 1 4 5.210285 11.78601
#> 5 1 9 1.021253 10.05061
#> 6 1 18 4.623846 12.09391Specifying the model
Each process is measured by one variable, with a loading of 1, so
LAMBDA is an identity matrix. ctModel() takes
the names of the time and id columns from its time and
id arguments, which default to 'time' and
'id'.
model <- ctModel(LAMBDA = diag(2),
manifestNames = c('stress', 'mood'), latentNames = c('stress', 'mood'))
model
#> ctsem model (continuous time)
#> 2 latent (stress, mood), 2 manifest (stress, mood)
#>
#> 13 free parameters
#>
#> 4 individually varying: T0m_stress, T0m_mood, mm_stress, mm_mood
#> This is a multilevel model. It estimates a 4 x 4 population covariance
#> over those parameters -- 4 standard deviations and 6 correlations on top of the 13 above.
#> Set indvarying = FALSE in a cell (see ?ctPar) for any that should not vary.
#>
#> T0MEANS
#>
#> stress T0m_stress
#> mood T0m_mood
#>
#> T0VAR
#> stress mood
#> stress T0var_stress 0
#> mood T0var_mood_stress T0var_mood
#>
#> DRIFT
#> stress mood
#> stress drift_stress drift_stress_mood
#> mood drift_mood_stress drift_mood
#>
#> DIFFUSION
#> stress mood
#> stress diff_stress 0
#> mood diff_mood_stress diff_mood
#>
#> CINT
#>
#> stress 0
#> mood 0
#>
#> LAMBDA
#> stress mood
#> stress 1 0
#> mood 0 1
#>
#> MANIFESTMEANS
#>
#> stress mm_stress
#> mood mm_mood
#>
#> MANIFESTVAR
#> stress mood
#> stress mvarstress 0
#> mood 0 mvarmoodPrinting the model shows each matrix, with the name of each free
parameter and the value of each fixed one. Everything not given to
ctModel() takes the defaults in the table above.
ctModelLatex(model) writes the same model as equations, and
opens them as a pdf if LaTeX is installed:
The first line is the distribution of the random effects. Each personโs starting values and measurement intercepts are drawn from a normal distribution, on the raw scale of the parameters, and then transformed. The next two lines are the dynamics, the two after them the measurement, and the last line the distribution of the random shocks over an interval.
To change a matrix, give it to ctModel(). A number fixes
a cell, and a name estimates it. This drift matrix would fix the effect
of mood on stress at zero:
The same model can be written in lavaan, Mplus or formula syntax,
which vignette('model-syntax') describes.
Fitting
fit <- ctFit(dat, model, cores = 2)By default ctFit() finds the maximum likelihood
estimates, integrating over the latent states and over the differences
between people. cores sets the number of CPU cores to use.
priors = TRUE adds weakly informative priors, which helps
with small data sets, and optimize = FALSE samples the
posterior instead of optimising. vignette('uncertainty')
compares these.
Reading the results
summary(fit) prints every part of the result. The
population values of the parameters are in popmeans:
s <- summary(fit)
s$popmeans
#> mean sd 2.5% 50% 97.5% mode
#> T0m_stress -0.104 0.108 -0.321 -0.103 0.106 -0.105
#> T0m_mood -0.042 0.098 -0.227 -0.043 0.169 -0.040
#> drift_stress -0.540 0.055 -0.654 -0.539 -0.437 -0.538
#> drift_stress_mood 0.034 0.033 -0.027 0.034 0.099 0.032
#> drift_mood_stress -0.235 0.029 -0.295 -0.233 -0.179 -0.235
#> drift_mood -0.347 0.032 -0.411 -0.346 -0.288 -0.347
#> diff_stress 0.866 0.051 0.769 0.865 0.967 0.863
#> diff_mood_stress -0.002 0.041 -0.084 -0.004 0.078 -0.002
#> diff_mood 0.642 0.032 0.580 0.642 0.708 0.643
#> mvarstress 0.366 0.036 0.305 0.363 0.443 0.364
#> mvarmood 0.368 0.022 0.327 0.367 0.414 0.366
#> mm_stress 3.062 0.081 2.914 3.061 3.223 3.064
#> mm_mood 5.096 0.063 4.977 5.097 5.225 5.096Each row is a parameter, with its estimate (mean),
standard error (sd) and 95% interval.
-
drift_stressanddrift_moodare the auto effects, per day. On its own, stress one unit above its equilibrium changes at a rate of about -0.5 units a day, and after one day aboutexp(-0.54), or 0.58, of the deviation is left. -
drift_mood_stressis the effect of stress on mood: more stress lowers the rate of change of mood.drift_stress_mood, the effect of mood on stress, is small and its interval includes zero. -
diff_stressanddiff_moodare the standard deviations of the random shocks.diff_mood_stressis a parameter for their correlation, and is not itself a correlation. The correlation is ins$parmatricesandctSummaryMatrices(fit)$estimate$DIFFUSIONcor. -
mvarstressandmvarmoodare the measurement error standard deviations. -
mm_stressandmm_moodare the average levels of the two variables, andT0m_stressandT0m_moodwhere the processes start relative to them.
The drift matrix as a whole decides whether the processes are stable and how fast they change. They are stable when every eigenvalue has a negative real part, and the eigenvalues give the time scale:
est <- ctSummaryMatrices(fit)$estimate
est$DRIFT
#> stress mood
#> stress -0.5380869 0.03192653
#> mood -0.2346860 -0.34671108
eigen(est$DRIFT)$values
#> [1] -0.4831845 -0.4016134
log(2) / abs(eigen(est$DRIFT)$values) # half-lives, in days
#> [1] 1.434539 1.725906Both eigenvalues are negative, and a disturbance to the system halves in one and a half to two days.
How much people differ is in popsd, the standard
deviations of the random effects:
s$popsd
#> mean sd 2.5% 50% 97.5% mode
#> T0m_stress 0.928 0.088 0.768 0.924 1.098 0.922
#> T0m_mood 0.851 0.085 0.691 0.846 1.029 0.842
#> mm_stress 0.709 0.059 0.598 0.706 0.829 0.707
#> mm_mood 0.514 0.058 0.411 0.513 0.643 0.512People differ in their typical stress by a standard deviation of about 0.7 and in their typical mood by about 0.5.
Since the data are simulated, the dynamic parameters can be set against the values that generated them:
pars <- c('drift_stress', 'drift_stress_mood', 'drift_mood_stress',
'drift_mood', 'diff_stress', 'diff_mood', 'mvarstress', 'mvarmood')
data.frame(truth = c(-0.5, 0, -0.25, -0.3, 0.8, 0.6, 0.4, 0.4),
s$popmeans[pars, c('mean', '2.5%', '97.5%')])
#> truth mean X2.5. X97.5.
#> drift_stress -0.50 -0.540 -0.654 -0.437
#> drift_stress_mood 0.00 0.034 -0.027 0.099
#> drift_mood_stress -0.25 -0.235 -0.295 -0.179
#> drift_mood -0.30 -0.347 -0.411 -0.288
#> diff_stress 0.80 0.866 0.769 0.967
#> diff_mood 0.60 0.642 0.580 0.708
#> mvarstress 0.40 0.366 0.305 0.443
#> mvarmood 0.40 0.368 0.327 0.414Every interval contains the generating value.
Effects over time
A cross effect in a continuous time model is an effect on a rate of change. The effect of stress on mood over a given time interval, the cross-lagged coefficient a discrete time model would estimate, depends on the interval:
ctDiscretePars(fit, times = seq(0, 10, by = 0.1), plot = TRUE)
A unit of stress is followed by lower mood, most strongly two to
three days later, when the effect is about -0.2. summary()
of ctDiscretePars(fit, times = ...) gives the peaks and
their times, and vignette('dynamics') explains these
curves.
Individual trajectories
ctPredict() gives the modelโs predictions for each
person over time. The plot shows the observations, and lines for each
personโs expected values given their earlier observations, with 95%
intervals. The lines jump at each observation, as it updates the
prediction. kalmanvec = 'ysmooth' uses all of a personโs
observations instead.
ctPredict(fit, subjects = 1:2, plot = TRUE)
ctSubjectPars() gives each personโs estimated
parameters, here their own typical levels and starting states. They are
close to the levels that generated the data:
sp <- ctSubjectPars(fit)
dim(sp) # draws x subjects x parameters
#> [1] 1 100 4
cor(sp[1, , 'mm_stress'], truelevels$mm_stress)
#> [1] 0.9474248A covariate
Age is in the data but not in the model. ctScoreTest()
tests, without refitting, whether a covariate would improve the model,
and estimates the effect it would have on each parameter:
covariates <- unique(dat[, c('id', 'age')])
ctScoreTest(fit, covariates = covariates, tests = 'covariates')
#> Score tests at the fitted model (laplace route, 100 subjects)
#>
#> Covariate age (linear): joint LM = 51.7, df = 17, p = 0.03
#> parameter estimate se estimate_natural p p_adj class
#> mm_stress 0.03280 0.00599 0.3280 <5e-04 0.0085 <NA>
#> popsd_T0m_mood -0.07500 0.03780 NA 0.0695 0.5490 <NA>
#> diff_mood 0.02300 0.01500 0.0286 0.1400 0.5490 <NA>
#> drift_mood -0.04870 0.03350 -0.0310 0.1510 0.5490 <NA>
#> mm_mood 0.00589 0.00455 0.0589 0.2040 0.5490 <NA>
#> mvarstress 0.08080 0.06300 0.0568 0.2150 0.5490 A
#> drift_stress_mood -0.03030 0.02650 -0.0303 0.2540 0.5490 <NA>
#> T0m_mood 0.00869 0.00796 0.0869 0.2710 0.5490 <NA>
#> diff_mood_stress -0.03660 0.03620 -0.0366 0.2900 0.5490 <NA>
#> mvarmood -0.01750 0.01850 -0.0123 0.3380 0.5540 <NA>Age affects the typical stress level, mm_stress, by
about 0.3 per standard deviation of age, and no other parameter stands
out. In the model, a covariate is a time independent predictor
(TIpredNames), and its effects are given in the
tipreds field of the parameters it affects. With
tipredDefault = FALSE it affects only those.
model2 <- ctModel(LAMBDA = diag(2),
manifestNames = c('stress', 'mood'), latentNames = c('stress', 'mood'),
TIpredNames = 'age', tipredDefault = FALSE,
MANIFESTMEANS = c('mm_stress, tipreds=c(age)', 'mm_mood'))
fit2 <- ctFit(dat, model2, cores = 2)
summary(fit2)$tipreds
#> mean sd 2.5% 50% 97.5% mode z
#> tip_age_mm_stress 0.313 0.057 0.204 0.314 0.429 0.316 5.446
anova(fit, fit2)
#> Likelihood-ratio tests, each fit against the one above it
#>
#> npar AIC BIC logLik -2LL Chisq Df Pr(>Chisq)
#> fit 23 13053 13191 -6503.4 13007
#> fit2 24 13028 13172 -6490.0 12980 26.854 1 2.194e-07 ***
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1ctPar() writes such cell strings, with fields for a
cellโs transform, its random effect and its covariate effects.
Checking the model
ctScoreTest() also tests whether parameters the model
holds fixed should differ between people, whether the dynamics depend on
the level of a process, and whether cells fixed at zero should be
free:
ctScoreTest(fit2)
#> Score tests at the fitted model (laplace route, 100 subjects)
#>
#> Unmodelled heterogeneity (LM: the variance with its covariances, against an
#> equal mixture of chi-square on df - 1 and df; z: the variance alone, one sided;
#> p: the stronger of the two; sd: the one-step estimate, raw scale):
#> parameter LM df z p p_adj sd sd_natural
#> drift_stress 11.400 5 -1.1700 0.0755 0.619 NA NA
#> drift_mood_stress 9.220 5 -0.9160 0.1380 0.619 NA NA
#> drift_mood 6.330 5 -0.7510 0.4000 0.846 NA NA
#> diff_mood_stress 6.070 5 0.0922 0.4160 0.846 0.0256 0.0256
#> diff_stress 4.440 5 -0.2080 0.6460 0.846 NA NA
#> mvarmood 4.070 5 -0.4270 0.7140 0.846 NA NA
#> mvarstress 1.370 5 -0.0616 0.7620 0.846 NA NA
#> diff_mood 1.830 5 -0.1460 0.7800 0.846 NA NA
#> drift_stress_mood 0.743 5 -0.2880 0.8460 0.846 NA NA
#> Covariances with: T0m_stress, T0m_mood, mm_stress, mm_mood
#>
#> A new dimension of variation: largest eigenvalue 2.32, p = 0.956; direction drift_mood 1, drift_stress -0.55, mvarmood 0.5, drift_mood_stress -0.42, mvarstress -0.36
#>
#> State dependence of the drift:
#> equation LM df p
#> stress 4.400 3 0.240
#> mood 0.824 3 0.842
#> all 5.270 6 0.552
#>
#> term equation LM p p_adj estimate se
#> stress*stress stress 2.36000 0.124 0.746 -0.02910 0.0190
#> mood*mood stress 0.66800 0.414 0.959 0.01910 0.0234
#> stress*mood mood 0.25600 0.613 0.959 0.01270 0.0251
#> stress*stress mood 0.22000 0.639 0.959 0.01080 0.0231
#> stress*mood stress 0.01000 0.920 0.975 -0.00348 0.0348
#> mood*mood mood 0.00102 0.975 0.975 NA NA
#> reads
#> DRIFT[stress,stress] varies with stress
#> DRIFT[stress,mood] varies with mood
#> DRIFT[mood,stress] varies with mood, or DRIFT[mood,mood] with stress
#> DRIFT[mood,stress] varies with stress
#> DRIFT[stress,stress] varies with mood, or DRIFT[stress,mood] with stress
#> DRIFT[mood,mood] varies with mood
#>
#> State dependence of the innovation sds:
#> equation LM df p
#> stress 1.96 2 0.387
#> mood 1.24 2 0.557
#> all 2.76 4 0.606
#>
#> term LM p p_adj estimate se
#> sd(stress) x exp(v * mood) 1.2300 0.266 0.615 -0.02740 0.0246
#> sd(mood) x exp(v * mood) 1.0400 0.307 0.615 0.02730 0.0267
#> sd(stress) x exp(v * stress) 0.3570 0.550 0.734 -0.01310 0.0219
#> sd(mood) x exp(v * stress) 0.0387 0.844 0.844 0.00589 0.0299
#>
#> Fixed cells, freed: joint LM = 0.72, df = 1, p = 0.404
#> cell LM p p_adj estimate se
#> MANIFESTVAR[mood,stress] 0.72 0.396 0.396 0.101 0.12
#>
#> Parameters depending on a subject's level (a random intercept):
#> level LM df p
#> mm_stress 9.670 9 0.508
#> mm_mood 0.101 9 1.000
#> all 19.800 18 0.678
#>
#> term LM p p_adj estimate se class
#> drift_mood_stress ~ mm_stress 4.23000 0.0397 0.715 0.0655 0.0319 <NA>
#> drift_stress_mood ~ mm_stress 2.65000 0.1030 0.873 -0.0622 0.0382 <NA>
#> diff_stress ~ mm_stress 1.97000 0.1610 0.873 0.0324 0.0231 <NA>
#> mvarstress ~ mm_stress 1.69000 0.1940 0.873 0.0319 0.0246 <NA>
#> diff_mood ~ mm_stress 1.18000 0.2770 0.994 0.0218 0.0200 <NA>
#> drift_stress ~ mm_mood 0.03040 0.8620 0.994 NA NA A
#> diff_mood_stress ~ mm_mood 0.02430 0.8760 0.994 NA NA C
#> drift_mood_stress ~ mm_mood 0.01520 0.9020 0.994 NA NA <NA>
#> diff_stress ~ mm_mood 0.01220 0.9120 0.994 NA NA <NA>
#> mvarmood ~ mm_mood 0.00798 0.9290 0.994 NA NA DNothing stands out once the tests are adjusted for their number
(p_adj). ctFitAdequacy() tests the modelโs
one-step-ahead predictions against the data, and
ctModelImprove() searches for a better model step by step.
vignette('score-tests') describes all three.
Where next
-
vignette('dynamics'): reading drift matrices, stability, time scales and effects over time. -
vignette('interventions'): time dependent predictors, with effects that are immediate, lasting or gradual. -
vignette('model-syntax'): models in lavaan, Mplus or formula syntax. -
vignette('measurement-models'): several indicators, and binary, ordinal, count and censored variables. -
vignette('laplace-multilevel'): random effects, and subjects nested in groups. -
vignette('uncertainty'): standard errors, sampling and priors. -
vignette('score-tests'): checking and improving a model. - The website has worked examples of a single long time series, growth curves, discrete time models, accelerated designs and the Kalman filter and smoother, and an article on why ctsem models change in continuous time.