ctsem v3.3.11


Monthly downloads



Continuous Time Structural Equation Modelling

Hierarchical continuous time state space modelling, for linear and nonlinear systems measured by continuous variables, with limited support for binary data. The subject specific dynamic system is modelled as a stochastic differential equation (SDE), measurement models are typically multivariate normal factor models. Linear mixed effects SDE's estimated via maximum likelihood and optimization are the default. Nonlinearities, (state dependent parameters) and random effects on all parameters are possible, using either max likelihood / max a posteriori optimization (with optional importance sampling) or Stan's Hamiltonian Monte Carlo sampling. See <https://github.com/cdriveraus/ctsem/raw/master/vignettes/hierarchicalmanual.pdf> for details. Priors may be used. For the conceptual overview of the hierarchical Bayesian linear SDE approach, see <https://www.researchgate.net/publication/324093594_Hierarchical_Bayesian_Continuous_Time_Dynamic_Modeling>. Exogenous inputs may also be included, for an overview of such possibilities see <https://www.researchgate.net/publication/328221807_Understanding_the_Time_Course_of_Interventions_with_Continuous_Time_Dynamic_Models> . Stan based functions are not available on 32 bit Windows systems at present. <https://cdriver.netlify.app/> contains some tutorial blog posts.


See the NEWS file for recent updates!

ctsem allows for easy specification and fitting of a range of continuous and discrete time dynamic models, including multiple indicators (dynamic factor analysis), multiple, potentially higher order processes, and time dependent (varying within subject) and time independent (not varying within subject) covariates. Classic longitudinal models like latent growth curves and latent change score models are also possible. Version 1 of ctsem provided SEM based functionality by linking to the OpenMx software, allowing mixed effects models (random means but fixed regression and variance parameters) for multiple subjects. For version 2 of the R package ctsem, we include a hierarchical specification and fitting routine that uses the Stan probabilistic programming language, via the rstan package in R. This allows for all parameters of the dynamic model to individually vary, using an estimated population mean and variance, and any time independent covariate effects, as a prior. Version 3 allows for state dependencies in the parameter specification (i.e. time varying parameters).

The curent manual is at https://cran.r-project.org/package=ctsem/vignettes/hierarchicalmanual.pdf. The original ctsem is documented in a JSS publication (Driver, Voelkle, Oud, 2017), and in R vignette form at https://cran.r-project.org/package=ctsemOMX/vignettes/ctsem.pdf, however these OpenMx based functions have been split off into a sub package, ctsemOMX.

To cite ctsem please use the citation(“ctsem”) command in R.

To install the github version and (if needed) configure your system, from a fresh R session run:

source(file = 'https://github.com/cdriveraus/ctsem/raw/master/installctsem.R')

If there are problems with the above script, you can try:

Manually install rstan, Rtools

remotes::install_github('cdriveraus/ctsem', INSTALL_opts = "--no-multiarch", dependencies = c("Depends", "Imports"))

Or just use the CRAN version, but rstan compiler setup is needed separately for some models:


Troubleshooting Rstan / Rtools install for Windows:

Ensure recent version of R and Rtools is installed. If the installctsem.R code has never been run before, be sure to run that (see above).

Place this line in ~/.R/makevars.win , and if there are other lines, delete them:

CXX14FLAGS += -mtune=native -march=native -Wno-ignored-attributes -Wno-deprecated-declarations

see for details

If makevars does not exist, re-run the install code above.

In case of compile errors like g++ not found, ensure the devtools package is installed:


and include the following in your .Rprofile, replacing c:/Rtools with the appropriate path – sometimes Rbuildtools/4.0/ .

Sys.setenv(PATH = paste("C:/Rtools/bin", Sys.getenv("PATH"), sep=";"))
Sys.setenv(PATH = paste("C:/Rtools/mingw_64/bin", Sys.getenv("PATH"), sep=";"))
Sys.setenv(BINPREF = "C:/Rtools/mingw_$(WIN)/bin/")

Functions in ctsem

Name Description
Oscillating Oscillating
ctDocs Get documentation pdf for ctsem
ctDiscretiseData Discretise long format continuous time (ctsem) data to specific timestep.
AnomAuth AnomAuth
ctCheckFit Check absolute fit of ctFit or ctStanFit object.
ctDensity ctDensity
ctDiscretePars ctDiscretePars
ctDeintervalise ctDeintervalise
ctCollapse ctCollapse Easily collapse an array margin using a specified function.
ctExample1 ctExample1
ctExample2 ctExample2
ctModelLatex Generate and optionally compile latex equation of subject level ctsem model.
ctExample1TIpred ctExample1TIpred
ctPlotArray Plots three dimensional y values for quantile plots
ctExample2level ctExample2level
ctStanContinuousPars ctStanContinuousPars
ctPoly Plots uncertainty bands with shading
ctExample4 ctExample4
ctExample3 ctExample3
ctIntervalise Converts absolute times to intervals for wide format ctsem panel data
ctKalman ctKalman
Kalman Kalman
ctStanGenerate Generate data from a ctstanmodel object
ctStanParMatrices Returns population system matrices from a ctStanFit object, and vector of values for free parameters.
ctStanDiscretePars ctStanDiscretePars
ctExtract Extract samples from a ctStanFit object
ctFit ctFit function placeholder
ctStanDiscreteParsPlot ctStanDiscreteParsPlot
ctStanUpdModel Update an already compiled and fit ctStanFit object
ctWideNames ctWideNames sets default column names for wide ctsem datasets. Primarily intended for internal ctsem usage.
ctLOO K fold cross validation for ctStanFit objects
ctLongToWide ctLongToWide Restructures time series / panel data from long format to wide format for ctsem analysis
ctGenerate ctGenerate
datastructure datastructure
ctStanGenerateFromFit Add a $generated object to ctstanfit object, with random data generated from posterior of ctstanfit object
ctStanParnames ctStanParnames
inv_logit Inverse logit
ctstantestdat ctstantestdat
stanoptimis Optimize / importance sample a stan or ctStan model.
summary.ctStanFit summary.ctStanFit
stan_unconstrainsamples Convert samples from a stanfit object to the unconstrained scale
isdiag Diagnostics for ctsem importance sampling
ctstantestfit ctstantestfit
log1p_exp log1p_exp
standatact_specificsubjects Adjust standata from ctsem to only use specific subjects
ctWideToLong ctWideToLong Convert ctsem wide to long format
ctIndplot ctIndplot
ctsem ctsem
ctModelHigherOrder Raise the order of a ctsem model object of type 'omx'.
ctModel Define a ctsem model
ctStanKalman Get Kalman filter estimates from a ctStanFit object
plot.ctStanModel Prior plotting
plot.ctStanFit plot.ctStanFit
stan_checkdivergences Analyse divergences in a stanfit object
stanWplot Runs stan, and plots sampling information while sampling.
ctStanModel Convert a frequentist (omx) ctsem model specification to Bayesian (Stan).
ctStanTIpredMarginal Plot marginal relationships between covariates and parameters for a ctStanFit object.
ctStanTIpredeffects Get time independent predictor effect estimates
ctStanFit ctStanFit
plot.ctsemFitMeasure Misspecification plot using ctCheckFit output
sdpcor2cov sdcor2cov
w32chk Check for non win32
ctStanFitUpdate Update a ctStanFit object
longexample longexample
ctStanPlotPost ctStanPlotPost
plot.ctKalmanDF Plots Kalman filter output from ctKalman.
ctStanPostPredict Compares model implied density and values to observed, for a ctStanFit object.
stan_postcalc Compute functions of matrices from samples of a stanfit object
stan_reinitsf Quickly initialise stanfit object from model and data
No Results!

Vignettes of ctsem

No Results!

Last month downloads


Type Package
Date 2020-09-16
License GPL-3
URL https://github.com/cdriveraus/ctsem
Encoding UTF-8
LazyData true
ByteCompile true
LinkingTo BH (>= 1.66.0-1), Rcpp (>= 0.12.16), RcppEigen (>=, RcppParallel (>= 5.0.1), rstan (>= 2.21), StanHeaders (>= 2.21.0), RcppParallel (>= 5.0.1)
SystemRequirements GNU make
NeedsCompilation yes
VignetteBuilder knitr
RoxygenNote 7.1.1
Biarch true
Packaged 2020-09-16 09:54:52 UTC; Driver
Repository CRAN
Date/Publication 2020-09-16 11:10:04 UTC

Include our badge in your README