| Title: | Multilevel Latent Time Series Models with 'R' and 'Stan' |
|---|---|
| Description: | Fit multilevel manifest or latent time-series models, including popular Dynamic Structural Equation Models (DSEM). The models can be set up and modified with user-friendly functions and are fit to the data using 'Stan' for Bayesian inference. Path models and formulas for user-defined models can be easily created with functions using 'knitr'. Asparouhov, Hamaker, & Muthen (2018) <doi:10.1080/10705511.2017.1406803>. |
| Authors: | Kenneth Koslowski [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-5296-5267>), Fabian Münch [aut] (ORCID: <https://orcid.org/0000-0001-5591-9901>), Tobias Koch [aut] (ORCID: <https://orcid.org/0000-0002-8143-3566>), Jana Holtmann [aut] (ORCID: <https://orcid.org/0000-0002-7949-0772>) |
| Maintainer: | Kenneth Koslowski <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 2.0.1.9000 |
| Built: | 2026-05-12 09:28:56 UTC |
| Source: | https://github.com/munchfab/mlts |
Simulated Data (from mlts_sim) for one time-series variable.
ar1_dataar1_data
ar1_dataA data frame with 2,500 rows and 3 columns:
Unit identifier
Time point
The time-series variable
Create Missings for Approximation of Continuous Time Dynamic Models
create_missings(data, tinterval, id, time, btw_vars = NULL)create_missings(data, tinterval, id, time, btw_vars = NULL)
data |
An object of class |
tinterval |
The step interval for approximation for a continuous time DSEM. The smaller the step interval, the better the approximation. |
id |
The variable in |
time |
The variable in |
btw_vars |
The names of between-level variables in the data to be added in newly created rows with NAs. |
A data.frame with missings imputed for use in mlts_fit.
# create some data for example data <- data.frame( id = rep(c(1, 2), each = 4), time = c(0, 3, 4, 6, 1, 4, 5, 7) ) # create missings to approximate continuous time process create_missings( data = data, id = "id", time = "time", tinterval = 1 # use time interval of 1 minute )# create some data for example data <- data.frame( id = rep(c(1, 2), each = 4), time = c(0, 3, 4, 6, 1, 4, 5, 7) ) # create missings to approximate continuous time process create_missings( data = data, id = "id", time = "time", tinterval = 1 # use time interval of 1 minute )
Computes descriptive statistics for one or more time-series variables, optionally within groups. For each variable (and group, if provided), the function returns sample size, number of complete observations, percentage of missing values, number of complete lag-1 pairs, central tendency, dispersion, skewness, kurtosis, and floor/ceiling effects.
describe_ts( data, ts, group = NULL, digits = 3, scale_min = NULL, scale_max = NULL, skew_type = 2, kurt_type = 2 )describe_ts( data, ts, group = NULL, digits = 3, scale_min = NULL, scale_max = NULL, skew_type = 2, kurt_type = 2 )
data |
A |
ts |
A character vector of variable names (columns in |
group |
Optional. A character string giving the name of a grouping
variable in |
digits |
Integer indicating the number of decimal places to which numeric statistics should be rounded. Default is 3. |
scale_min, scale_max
|
Optional numeric values specifying the minimum and
maximum of the measurement scale for computing floor and ceiling
percentages. If |
skew_type |
Integer (1, 2, or 3) passed to |
kurt_type |
Integer (1, 2, or 3) passed to |
For each time-series variable, the function removes NA values before
computing summary statistics. Skewness and kurtosis are obtained from
e1071::skewness and e1071::kurtosis, respectively, using the
skew_type and kurt_type arguments. When the standard deviation
is zero, missing, or when fewer than four complete observations are
available, both skewness and kurtosis are set to NA.
Floor and ceiling effects are defined as the percentage of non-missing
observations equal to scale_min and scale_max, respectively.
Lag-1 completeness is computed as the number of adjacent observation pairs
where both the current and next observation are non-missing. If
group = NULL, this computation does not account for clustering
or overnight gaps—that is, the function assumes the
data form a single continuous time series, and lag-1 pairs may span across
natural breaks in the data.
A data.frame with one row per variable per group, containing:
group — group identifier (omitted if group = NULL)
ts_var — name of time series variable
N — total number of observations (including NAs)
N_comp — number of non-missing observations
miss_pc — percent missing
N_lag1_comp — number of complete lag-1 pairs
M — mean
Mdn — median
SD — standard deviation
Skew — sample skewness (as returned by e1071::skewness
with the specified skew_type)
Kurtosis — sample kurtosis (as returned by
e1071::kurtosis with the specified kurt_type)
floor_pc — percent at scale_min
ceiling_pc — percent at scale_max
## Not run: # Example with grouping describe_ts(data = df, ts = c("x", "y"), group = "id") # Example without grouping describe_ts(data = df, ts = "x") ## End(Not run)## Not run: # Example with grouping describe_ts(data = df, ts = c("x", "y"), group = "id") # Example without grouping describe_ts(data = df, ts = "x") ## End(Not run)
Fit Bayesian Multilevel Manifest or Latent Time-Series Models
mlts_fit( model, data = NULL, id, group = NULL, ts, covariates = NULL, outcomes = NULL, outcome_pred_btw = NULL, center_covs = TRUE, time = NULL, tinterval = NULL, beep = NULL, days = NULL, n_overnight_NAs, max_NA_seq = NULL, na.rm = FALSE, iter = 500, chains = 2, cores = 2, monitor_person_pars = FALSE, monitor_all_pars = FALSE, get_SD_latent = FALSE, fit_model = TRUE, print_message = TRUE, print_warning = TRUE, ... )mlts_fit( model, data = NULL, id, group = NULL, ts, covariates = NULL, outcomes = NULL, outcome_pred_btw = NULL, center_covs = TRUE, time = NULL, tinterval = NULL, beep = NULL, days = NULL, n_overnight_NAs, max_NA_seq = NULL, na.rm = FALSE, iter = 500, chains = 2, cores = 2, monitor_person_pars = FALSE, monitor_all_pars = FALSE, get_SD_latent = FALSE, fit_model = TRUE, print_message = TRUE, print_warning = TRUE, ... )
model |
|
data |
An object of class |
id |
Character. The variable in |
group |
Character. The variable in |
ts |
Character. The variable(s) in |
covariates |
Named character vector. An optional named vector of
characters to refer to predictors of random effects as specified in the |
outcomes |
Named character vector. Similar to |
outcome_pred_btw |
Named character vector. Similar to |
center_covs |
Logical. Between-level covariates used as predictors of random effects
will be grand-mean centered before model fitting by default. Set |
time |
Character. The variable in |
tinterval |
The step interval for approximating equally spaced observations in time by insertion of missing values, to be specified with respect to the time stamp variable provided in time. Procedure for inserting missing values resembles the procedure for time shift transformation as described in Asparouhov, Hamaker, & Muthén (2018). |
beep |
Character. The variable in |
days |
Optional. If a running beep identifier is provided via the |
n_overnight_NAs |
Optional. The number of |
max_NA_seq |
Integer. Specify a maximum number of consecutive missing values. Can decrease estimation times drastically in the presence of very long sequences of missing values (e.g., when setting tinterval to values of small time steps). |
na.rm |
logical. Per default, missing values remain in the data and
will be imputed during model estimation. Set to |
iter |
A positive integer specifying the number of iterations for each chain (including 50% used as warmup). The default is 500. |
chains |
A positive integer specifying the number of Markov chains. The default is 2. |
cores |
The number of cores to use when executing the Markov chains in parallel.
The default is 2 (see |
monitor_person_pars |
Logical. Should person parameters (i.e., values of the latent variables) be stored? Default is FALSE. |
monitor_all_pars |
Logical. Should all parameters be stored? Default is FALSE. |
get_SD_latent |
Logical. Set to |
fit_model |
Logical. Set to FALSE to avoid fitting the model which may be helpful to inspect prepared data used for model estimation (default = TRUE). |
print_message |
Logical. Print messages based on defined inputs (default = TRUE). |
print_warning |
Logical. Print warnings based on defined inputs (default = TRUE). |
... |
Additional arguments passed to |
An object of class mltsfit.
The object is a list containing the following components:
model |
the model object passed to |
data |
the preprocessed data used for fitting the model |
param.labels |
a |
pop.pars.summary |
a |
person.pars.summary |
if |
standata |
a |
stanfit |
an object of class |
posteriors |
an |
Asparouhov, T., Hamaker, E. L., & Muthén, B. (2018). Dynamic Structural Equation Models. Structural Equation Modeling: A Multidisciplinary Journal, 25(3), 359–388. doi:10.1080/10705511.2017.1406803
# build simple vector-autoregressive mlts model for two time-series variables var_model <- mlts_model(q = 2) # fit model with (artificial) dataset ts_data fit <- mlts_fit( model = var_model, data = ts_data, ts = c("Y1", "Y2"), # time-series variables id = "ID", # cluster identifier variable time = "time", # time variable tinterval = 1 # interval for approximation of equidistant measurements, ) # inspect model summary summary(fit)# build simple vector-autoregressive mlts model for two time-series variables var_model <- mlts_model(q = 2) # fit model with (artificial) dataset ts_data fit <- mlts_fit( model = var_model, data = ts_data, ts = c("Y1", "Y2"), # time-series variables id = "ID", # cluster identifier variable time = "time", # time variable tinterval = 1 # interval for approximation of equidistant measurements, ) # inspect model summary summary(fit)
Build a multilevel latent time series model
mlts_model( class = c("VAR"), q, p = NULL, max_lag = c(1, 2, 3), btw_factor = TRUE, btw_model = NULL, equal_loads_levels = FALSE, fix_dynamics = FALSE, fix_inno_vars = FALSE, fix_inno_covs = TRUE, inno_covs_zero = FALSE, inno_covs_dir = NULL, fixef_zero = NULL, ranef_zero = NULL, ranef_pred = NULL, out_pred = NULL, out_pred_add_btw = NULL, group = NULL, is_exogenous = NULL, incl_t0_effects = NULL, incl_interaction_effects = NULL, censor_left = NULL, censor_right = NULL, silent = FALSE )mlts_model( class = c("VAR"), q, p = NULL, max_lag = c(1, 2, 3), btw_factor = TRUE, btw_model = NULL, equal_loads_levels = FALSE, fix_dynamics = FALSE, fix_inno_vars = FALSE, fix_inno_covs = TRUE, inno_covs_zero = FALSE, inno_covs_dir = NULL, fixef_zero = NULL, ranef_zero = NULL, ranef_pred = NULL, out_pred = NULL, out_pred_add_btw = NULL, group = NULL, is_exogenous = NULL, incl_t0_effects = NULL, incl_interaction_effects = NULL, censor_left = NULL, censor_right = NULL, silent = FALSE )
class |
Character. Indicating the model type to be specified. For now
restricted to |
q |
Integer. The number of time-varying constructs. |
p |
Integer. For multiple-indicator models, specify a vector of length
|
max_lag |
Integer. The maximum lag of the autoregressive effect to be included in the model. The maximum is 3. Defaults to 1. |
btw_factor |
Logical. If |
btw_model |
A list to indicate for which manifest indicator variables a common between-level factor should be modeled (see Details for detailed instructions). At this point restricted to one factor per latent construct. |
equal_loads_levels |
Logical. For multiple-indicator model with |
fix_dynamics |
Logical. Fix all random effect variances of autoregressive and cross-lagged effects to zero (constraining parameters to be equal across clusters). |
fix_inno_vars |
Logical. Fix all random effect variances of innovation variances to zero (constraining parameters to be equal across clusters). |
fix_inno_covs |
Logical. Fix all random effect variances of innovation covariances to zero (constraining parameters to be equal across clusters). |
inno_covs_zero |
Logical. Set to |
inno_covs_dir |
For bivariate VAR models with person-specific innovation covariances,
a latent variable approach is applied (for a detailed description, see Hamaker et al., 2018).
by specifying an additional factor that loads onto the contemporaneous innovations of both constructs,
capturing the shared variance of innovations, that is not predicted by the previous time points.
The loading parameters of this latent factor, however, have to be restricted in accordance with
researchers assumptions about the sign of the association between innovations across construct.
Hence, if innovations at time $t$ are assumed to be positively correlated across clusters, set the
argument to |
fixef_zero |
Character. A character vector to index which fixed effects
(referring to the parameter labels in |
ranef_zero |
Character. A character vector to index which random effect variances
(referring to the parameter labels in |
ranef_pred |
A character vector or a named list. Include between-level covariate(s)
as predictor(s) of all random effects in |
out_pred |
A character vector or a named list. Include between-level outcome(s)
to be regressed on all random effects in |
out_pred_add_btw |
A character vector. If |
group |
An integer specifying the number of groups (not yet supported). Add a binary coded (0 vs. 1) variable to include
group differences in fixed effects (intercepts). When dynamic or variance parameters
are allowed to vary by cluster, you can enter the grouping variable to |
is_exogenous |
Integer or a vector of integers. Indicate if any of the constructs should be treated as exogenous (i.e., no latent mean centering will be performed). Probable use case: Adding a dichotomous time-varying predictor variable. |
incl_t0_effects |
A character vector. Experimental: Add contemporaneous effects to the model.
For example, to include an effect of the first construct on the second construct at time $t$,
following the general pattern for naming of dynamic parameters in the mlts framework, can be included by
specifying |
incl_interaction_effects |
A character vector. Add interaction terms on
the dynamic within-level. For example, to add an interaction term between the first
construct at time $t$ (lag of 0) and the second construct at $t-1$ (lag of 1) to
the prediction of the second construct at time $t$ specify |
censor_left |
Numeric. If an input is provided (i.e., a single numeric value) a left-censored
version of the model will be estimated by treating all observations (of manifest indicators)
at the censoring threshold (i.e., usually the lower bound of the scale) to be treated as missing during model estimation.
These missing values (observations at the value of |
censor_right |
Numeric. Developmental. Similar to |
silent |
logical. Set to |
An object of class data.frame with the following columns:
Model |
Indicates if the parameter in the respective row is part of the structural, or the measurement model (if multiple indicators per construct are provided) |
Level |
Parameter on the between- or within-level. |
Type |
Describes the parameter type. |
Param |
Parameter names to be referred to in arguments of |
Param_Label |
Parameter labels (additional option to address specific parameters). |
isRandom |
Indicates which within-level parameters are modeled as random (1) or a constant across clusters (0). |
Constraint |
Optional. Included if multiple-indicators per construct (p > 1) are provided.
Constraints on measurement model parameters can be changed by overwriting the respective value
in |
prior_type |
Contains the parameters' prior distribution used in |
prior_location |
Location values of the parameters' prior distribution used
in |
prior_scale |
Scale values of the parameters' prior distribution used
in |
Hamaker, E. L., Asparouhov, T., Brose, A., Schmiedek, F., & Muthén, B. (2018). At the frontiers of modeling intensive longitudinal data: Dynamic structural equation models for the affective measurements from the COGITO study. Multivariate behavioral research, 53(6), 820-841. doi:10.1080/00273171.2018.1446819
# To illustrate the general model building procedure, starting with a simple # two-level AR(1) model with person-specific individual means, AR effects, # and innovation variances (the default option when using mlts_model() and q = 1). model <- mlts_model(q = 1) # All model parameters (with their labels stored in model$Param) can be inspected by calling: model # Possible model extensions/restrictions: # 1. Introducing additional parameter constraints, such as fixing specific # parameters to a constant value by setting the respective random effect # variances to zero, such as e.g. (log) innovation variances model <- mlts_model(q = 1, ranef_zero = "ln.sigma2_1") # Note that setting the argument `fix_inno_vars` to `TRUE` provides # a shortcut to fixing the innovation variances of all constructs # (if q >= 1) to a constant. # 2. Including a multiple indicator model, where the construct is measured by # multiple indicators (here, p = 3 indicators) model <- mlts_model( q = 1, # the number of time-varying constructs p = 3, # the number of manifest indicators # assuming a common between-level factor (the default) btw_factor = TRUE ) # 3. Incorporating between-level variables. For example, inclusion of # an additional between-level variable ("cov1") as predictor of all # (ranef_pred = "cov1") or a specific set of random effects # (ranef_pred = list("phi(1)_11") = "cov1"), an external outcome (e.g., "out1") # to be predicted by all (out_pred = "out1") or specific random effects # (out_pred = list("out1" = c("etaB_1", "phi(1)_11")), using the latent # between-level factor trait scores (etaB_1) and individual first-order # autoregressive effects (phi(1)_11) as joint predictors of outcome "out1". model <- mlts_model( q = 1, p = 3, fix_inno_vars = TRUE, ranef_pred = "cov1", out_pred = list("out1" = c("etaB_1", "phi(1)_11")) ) # Note that the names of the random effect parameters must match the # parameter labels provided in model$Param, the result of the # mlts_model()-functions.# To illustrate the general model building procedure, starting with a simple # two-level AR(1) model with person-specific individual means, AR effects, # and innovation variances (the default option when using mlts_model() and q = 1). model <- mlts_model(q = 1) # All model parameters (with their labels stored in model$Param) can be inspected by calling: model # Possible model extensions/restrictions: # 1. Introducing additional parameter constraints, such as fixing specific # parameters to a constant value by setting the respective random effect # variances to zero, such as e.g. (log) innovation variances model <- mlts_model(q = 1, ranef_zero = "ln.sigma2_1") # Note that setting the argument `fix_inno_vars` to `TRUE` provides # a shortcut to fixing the innovation variances of all constructs # (if q >= 1) to a constant. # 2. Including a multiple indicator model, where the construct is measured by # multiple indicators (here, p = 3 indicators) model <- mlts_model( q = 1, # the number of time-varying constructs p = 3, # the number of manifest indicators # assuming a common between-level factor (the default) btw_factor = TRUE ) # 3. Incorporating between-level variables. For example, inclusion of # an additional between-level variable ("cov1") as predictor of all # (ranef_pred = "cov1") or a specific set of random effects # (ranef_pred = list("phi(1)_11") = "cov1"), an external outcome (e.g., "out1") # to be predicted by all (out_pred = "out1") or specific random effects # (out_pred = list("out1" = c("etaB_1", "phi(1)_11")), using the latent # between-level factor trait scores (etaB_1) and individual first-order # autoregressive effects (phi(1)_11) as joint predictors of outcome "out1". model <- mlts_model( q = 1, p = 3, fix_inno_vars = TRUE, ranef_pred = "cov1", out_pred = list("out1" = c("etaB_1", "phi(1)_11")) ) # Note that the names of the random effect parameters must match the # parameter labels provided in model$Param, the result of the # mlts_model()-functions.
Create TeX Model Formula from mlts model object
mlts_model_formula( model, file = NULL, keep_tex = FALSE, ts = NULL, covariates = NULL, outcomes = NULL )mlts_model_formula( model, file = NULL, keep_tex = FALSE, ts = NULL, covariates = NULL, outcomes = NULL )
model |
A model built with |
file |
An optional string containing the name of the file and file path. Has to end with .pdf file format. |
keep_tex |
Logical. Should the TeX file be kept (additional to the
Rmd file)? Defaults to |
ts |
To be included in future releases. An optional character vector containing the names of the time-series variables or indicators. |
covariates |
To be included in future releases. An optional character vector containing the names of the between-level covariates. |
outcomes |
To be included in future releases. An optional character vector containing the names of the between-level outcomes. |
An RMarkdown file that is automatically rendered to a pdf document.
# build a simple vector-autoregressive mlts model with two time-series variables var_model <- mlts_model(q = 2) # create formula from the specified model mlts_model_formula(model = var_model)# build a simple vector-autoregressive mlts model with two time-series variables var_model <- mlts_model(q = 2) # create formula from the specified model mlts_model_formula(model = var_model)
Deprecated. Please use mlts_paths.
mlts_model_paths( model, file = NULL, add_png = FALSE, keep_tex = FALSE, ts = NULL, covariates = NULL, outcomes = NULL )mlts_model_paths( model, file = NULL, add_png = FALSE, keep_tex = FALSE, ts = NULL, covariates = NULL, outcomes = NULL )
model |
A model built with |
file |
An optional string containing the name of the file and file path. Has to end with .pdf file format. |
add_png |
Logical. Set to |
keep_tex |
Logical. Should the TeX file be kept (additional to the
Rmd file)? Defaults to |
ts |
To be included in future releases. An optional character vector containing the names of the time-series variables or indicators. |
covariates |
To be included in future releases. An optional character vector containing the names of the between-level covariates. |
outcomes |
To be included in future releases. An optional character vector containing the names of the between-level outcomes. |
An RMarkdown file that is automatically rendered to a pdf document.
# build a simple vector-autoregressive mlts model with two time-series variables var_model <- mlts_model(q = 2) # create a pathmodel from the specified model mlts_model_paths(model = var_model)# build a simple vector-autoregressive mlts model with two time-series variables var_model <- mlts_model(q = 2) # create a pathmodel from the specified model mlts_model_paths(model = var_model)
The mlts_paths function depcits models specified using mlts_model as a
path diagram.
mlts_paths( model, asp_decomp = 0.25, asp_w_b = 0.5, fig_margins.x = c(0, 8), fig_margins.y = c(0, 8), width = 7, height = 5, file = NULL, asp = height/width, family = "serif", cex_b = 0.8, cex_w = 1, cex_decomp = 1, cex_loads = 0.8, b_style = "h", w_y_offset = 0, decomp_F_y_offset = 4, arrHead_w = 0.16, arrHead_b = 0.16, scale_decomp_ind = 0.35, scale_decomp_F = 0.45, scale_within = 0.3, scale_within_inno = 0.2, scale_between = 0.3, scale_int = 0.25, lwd_nodes = 1.7, rand_dot_pos = 0.4, units = "in", res = 700, pointsize = 10, type = "cairo", y_ind_labs = NULL, y_fac_labs = NULL, y_fac_lab_sep = ",", remove_lag_lab = FALSE, adj_load_x = 1.25, ... )mlts_paths( model, asp_decomp = 0.25, asp_w_b = 0.5, fig_margins.x = c(0, 8), fig_margins.y = c(0, 8), width = 7, height = 5, file = NULL, asp = height/width, family = "serif", cex_b = 0.8, cex_w = 1, cex_decomp = 1, cex_loads = 0.8, b_style = "h", w_y_offset = 0, decomp_F_y_offset = 4, arrHead_w = 0.16, arrHead_b = 0.16, scale_decomp_ind = 0.35, scale_decomp_F = 0.45, scale_within = 0.3, scale_within_inno = 0.2, scale_between = 0.3, scale_int = 0.25, lwd_nodes = 1.7, rand_dot_pos = 0.4, units = "in", res = 700, pointsize = 10, type = "cairo", y_ind_labs = NULL, y_fac_labs = NULL, y_fac_lab_sep = ",", remove_lag_lab = FALSE, adj_load_x = 1.25, ... )
model |
|
asp_decomp |
A numeric value specifying the aspect ratio for the decomposition plot region. Defaults to 0.25. |
asp_w_b |
A numeric value specifying the aspect ratio between the within-level and between-level sections. Defaults to 0.5. |
fig_margins.x |
A numeric vector of length 2 defining the horizontal margins
of the plot. Defaults to |
fig_margins.y |
A numeric vector of length 2 defining the vertical margins
of the plot. Defaults to |
width |
Width of the plot in inches. Defaults to 7. |
height |
Height of the plot in inches. Defaults to 5. |
file |
A character string specifying the path to save the plot. If |
asp |
The overall aspect ratio of the plot, computed as |
family |
Font family used in the plot. Defaults to |
cex_b |
Numeric value specifying the scaling of text in the between-level section. Defaults to 0.8. |
cex_w |
Numeric value specifying the scaling of text in the within-level section. Defaults to 0.8. |
cex_decomp |
Numeric value specifying the scaling of text in the decomposition section. Defaults to 0.8. |
cex_loads |
Numeric value specifying the scaling of text of loading parameters. Defaults to 0.8. |
b_style |
A character string specifying the style of the between-level plot
("h" for horizontal). Defaults to |
w_y_offset |
Numeric value specifying the vertical width of the within-level part. Defaults to 0. |
decomp_F_y_offset |
Numeric value to control the vertical space between manifest indicators and latent factors in the decomposition part of the path model. Defaults to 4. |
arrHead_w |
Numeric values controlling the arrowhead size for within-level paths. Defaults to 0.16. |
arrHead_b |
Numeric values controlling the arrowhead size for between-level paths. Defaults to 0.16. |
scale_decomp_ind |
Numeric. Specify the scaling factor for manifest indicators in the decomposition section. |
scale_decomp_F |
Numeric. Specify the scaling factor for latent factors in the decomposition section. |
scale_within |
Numeric. Specify the scaling factor for latent factors in the within-level section. |
scale_within_inno |
Numeric. Specify the scaling factor for innovations in the within-level section. |
scale_between |
Numeric. Specify the scaling factor for factors in the between-level section. |
scale_int |
Numeric. Specify the scaling factor for interaction factors in the within-level section. |
lwd_nodes |
Line width for node borders in the plot. Defaults to 1.7. |
rand_dot_pos |
Numeric value controlling the random dot position in the plot. Defaults to 0.5. |
units |
A character string specifying the units for saving the plot. Defaults to "in". |
res |
The nominal resolution in ppi. Defaults to 320. |
pointsize |
Numeric value specifying the font point size for the plot. Defaults to 10. |
type |
A character string specifying the file type for the saved plot (e.g., "cairo"). Defaults to "cairo". |
y_ind_labs |
A vector of character strings with names of observed variables. |
y_fac_labs |
A vector of character strings with factor labels to replace numeric indices in parameter names. |
y_fac_lab_sep |
A character string to separate multiple factor labels. Defaults to ",". |
remove_lag_lab |
Logical. Remove lag index from phi-parameter labels. Defaults to |
adj_load_x |
Numeric value specifying the x-axis offset loading parameter labels. Defaults to 1.25. |
... |
Additional arguments passed to internal plotting functions. |
This function calculates positions, radii, and labels for nodes and arrows based on the model structure and its parameters. It divides the plot into sections:
Decomposition: Shows the breakdown of observed variables into within- and between-level components.
Within-Level Dynamics: Illustrates autoregressive and cross-lagged paths between variables at the within level.
Between-Level Dynamics: Depicts random effects, covariates, and their interrelations at the between level.
Depending on the model structure (e.g., maximum lag, number of random effects, presence of interaction terms), the function dynamically adjusts the visualization.
A graphical object representing the path diagram of the model.
# A two-level second-order autoregressive model model <- mlts_model(q = 1, max_lag = 2) # Plot the paths mlts_paths(model)# A two-level second-order autoregressive model model <- mlts_model(q = 1, max_lag = 2) # Plot the paths mlts_paths(model)
Plot results of mlts
mlts_plot( fit, type = c("fe", "re", "re.cor", "int"), bpe = c("median", "mean"), what = c("all", "Fixed effect", "Random effect SD", "RE correlation", "Outcome prediction", "RE prediction", "Item intercepts", "Loading", "Measurement Error SD"), sort_est = NULL, xlab = NULL, ylab = NULL, facet_ncol = 1, dot_size = 1, dot_color = "black", dot_shape = 1, errorbar_color = "black", errorbar_width = 0.3, add_true = FALSE, true_color = "red", true_shape = 22, true_size = 1, hide_xaxis_text = TRUE, par_labels = NULL, labels_as_expressions = FALSE )mlts_plot( fit, type = c("fe", "re", "re.cor", "int"), bpe = c("median", "mean"), what = c("all", "Fixed effect", "Random effect SD", "RE correlation", "Outcome prediction", "RE prediction", "Item intercepts", "Loading", "Measurement Error SD"), sort_est = NULL, xlab = NULL, ylab = NULL, facet_ncol = 1, dot_size = 1, dot_color = "black", dot_shape = 1, errorbar_color = "black", errorbar_width = 0.3, add_true = FALSE, true_color = "red", true_shape = 22, true_size = 1, hide_xaxis_text = TRUE, par_labels = NULL, labels_as_expressions = FALSE )
fit |
An object of class |
type |
Type of plot.
type = "fe" (Default)
Forest-plot of model coefficients.
type = "re"
Plot of individual (random) effects
type = "int"
Experimental: Plot within-level interactions.
type = "re.cor"
Combined plot depicting the distribution of individual parameter
estimates (posterior summary statistics as provided by |
bpe |
The Bayesian point estimate is, by default, the median of the
posterior distribution ( |
what |
Character. For |
sort_est |
Add parameter label for sorting of random effects. |
xlab |
Title for the x axis. |
ylab |
Title for the y axis. |
facet_ncol |
Number of facet columns (see |
dot_size |
numeric, size of the dots that indicate the point estimates. |
dot_color |
character. indicating the color of the point estimates. |
dot_shape |
numeric. shape of the dots that indicate the point estimates. |
errorbar_color |
character. Color of error bars. |
errorbar_width |
integer. Width of error bars. |
add_true |
logical. If model was fitted with simulated data using |
true_color |
character. Color of points depicting true population parameter used in the data generation. |
true_shape |
integer. Shape of points depicting true population parameter used in the data generation. |
true_size |
integer. Size of points depicting true population parameter used in the data generation. |
hide_xaxis_text |
logical. Hide x-axis text if set to |
par_labels |
character vector. User-specified labels for random effect parameters can be specified. |
labels_as_expressions |
logical. Should parameter names on plot labels be printed
as mathematical expressions? Defaults to |
Returns a ggplot-object .
# build simple vector-autoregressive mlts model for two time-series variables var_model <- mlts_model(q = 2) # fit model with (artificial) dataset ts_data fit <- mlts_fit( model = var_model, data = ts_data, ts = c("Y1", "Y2"), # time-series variables id = "ID", # identifier variable time = "time", tinterval = 1 # interval for approximation of continuous-time dynamic model, ) # inspect model summary mlts_plot(fit, type = "fe", what = "Fixed effect")# build simple vector-autoregressive mlts model for two time-series variables var_model <- mlts_model(q = 2) # fit model with (artificial) dataset ts_data fit <- mlts_fit( model = var_model, data = ts_data, ts = c("Y1", "Y2"), # time-series variables id = "ID", # identifier variable time = "time", tinterval = 1 # interval for approximation of continuous-time dynamic model, ) # inspect model summary mlts_plot(fit, type = "fe", what = "Fixed effect")
The mlts_posterior_sample() function generates replicated datasets from a fitted
mlts model using draws from the posterior distribution. The function can
simulate data under the population model or based on individual-specific (random effect) parameters.
mlts_posterior_sample( fit, draw_person_pars = FALSE, n_draws = 10, draws = NULL, as_matrix = TRUE )mlts_posterior_sample( fit, draw_person_pars = FALSE, n_draws = 10, draws = NULL, as_matrix = TRUE )
fit |
An object of class |
draw_person_pars |
Logical. If |
n_draws |
Integer. Number of posterior draws to use for simulating replicated datasets. Ignored if |
draws |
Optional integer vector indicating specific posterior draw indices to use. If |
as_matrix |
Logical. Return replications of each variable as a matrix with |
The function extracts posterior samples of population-level (and optionally individual-level) parameters
from a fitted mlts model and simulates replicated datasets from the posterior predictive distribution.
Each replication corresponds to a different posterior draw and reflects uncertainty in the model's parameters.
See PPC for an overview on graphical posterior predictive checks and how they can be performed.
If draw_person_pars = TRUE, the function uses sampled person-specific random effects and covariate effects
from the posterior to generate new data at the individual level. This requires that the model was fitted with
monitor_person_pars = TRUE in mlts_fit. If this condition is not met, the function will
throw an error.
Posterior draws are either selected with the maximum distance between posterior samples (n_draws) or specified manually using the draws argument.
Optionally, left or right censoring is respected in the simulated data if such constraints were present in the model.
A list of replicated datasets, each as a data.frame with columns:
Y_repReplication number.
IDSubject/cluster ID.
timeTime point.
One column per time-series variable defined in the model.
mlts_pp_check for plotting posterior predictive checks.
## Not run: # build a simple vector-autoregressive mlts model with two time-series variables var_model <- mlts_model(q = 2) # simulate data from this model with default true values # (true values are randomly drawn from normal distribution) var_data <- mlts_sim( model = var_model, N = 50, TP = 30, # number of units and number of measurements per unit default = TRUE # use default parameter values ) # fit model fit <- mlts_fit( model = var_model, data = var_data, id = "ID", ts = c("Y1", "Y2"), time = "time", monitor_person_pars = TRUE ) # Simulate 20 replications from the posterior yreps <- mlts_posterior_sample(fit = fit, n_draws = 20) # Include person-specific parameters in simulation yreps <- mlts_posterior_sample(fit = fit, draw_person_pars = TRUE) # Use specific posterior draws yreps <- mlts_posterior_sample(fit = fit, draws = c(10, 50, 100)) ## End(Not run)## Not run: # build a simple vector-autoregressive mlts model with two time-series variables var_model <- mlts_model(q = 2) # simulate data from this model with default true values # (true values are randomly drawn from normal distribution) var_data <- mlts_sim( model = var_model, N = 50, TP = 30, # number of units and number of measurements per unit default = TRUE # use default parameter values ) # fit model fit <- mlts_fit( model = var_model, data = var_data, id = "ID", ts = c("Y1", "Y2"), time = "time", monitor_person_pars = TRUE ) # Simulate 20 replications from the posterior yreps <- mlts_posterior_sample(fit = fit, n_draws = 20) # Include person-specific parameters in simulation yreps <- mlts_posterior_sample(fit = fit, draw_person_pars = TRUE) # Use specific posterior draws yreps <- mlts_posterior_sample(fit = fit, draws = c(10, 50, 100)) ## End(Not run)
Developemental This function plots posterior predictive distributions of one or multiple fitted mlts.fit models.
Simulated data from posterior draws are compared to the observed data to visually assess model fit.
mlts_pp_check( fit, fit_list = NULL, ts = NULL, y_reps = NULL, by_cluster = FALSE, by_group = FALSE, cluster_ids = NULL, draw_person_pars = FALSE, n_draws = 10, draws = NULL, add_y_obs = TRUE, model_lab = NULL, y_rep_col = NULL, y_obs_col = "#009E73", y_obs_lw = 1.1, y_rep_lw = 0.5, y_rep_alpha = 0.5 )mlts_pp_check( fit, fit_list = NULL, ts = NULL, y_reps = NULL, by_cluster = FALSE, by_group = FALSE, cluster_ids = NULL, draw_person_pars = FALSE, n_draws = 10, draws = NULL, add_y_obs = TRUE, model_lab = NULL, y_rep_col = NULL, y_obs_col = "#009E73", y_obs_lw = 1.1, y_rep_lw = 0.5, y_rep_alpha = 0.5 )
fit |
A fitted model object of class |
fit_list |
An optional list of fitted |
ts |
Optional vector of variable names to include in the plot. |
y_reps |
Optional. A list of posterior predictive samples (as returned by |
by_cluster |
Logical. If |
by_group |
Logical. If |
cluster_ids |
Optional vector of cluster IDs to include in the plot. If |
draw_person_pars |
Logical. If |
n_draws |
Integer. Number of posterior draws to use for generating replicated datasets. Defaults to 20.
Ignored if |
draws |
Optional vector of indices specifying which posterior draws to use. If |
add_y_obs |
Logical. Whether to include the observed data distribution in the plot. Defaults to |
model_lab |
Optional character vector with labels for each model in |
y_rep_col |
Optional vector of colors for the posterior predictive densities of each model. If |
y_obs_col |
Color for the observed data distribution. Default is |
y_obs_lw |
Line width of the observed data density curve. Default is |
y_rep_lw |
Line width of the observed data density curve. Default is |
y_rep_alpha |
Alpha transparency for the predictive density curves. Default is |
This function performs graphical posterior predictive checks by overlaying kernel density estimates of replicated
data from the posterior with the observed data. This can be used to visually assess how well a fitted model captures
key distributional aspects of the observed time series. If fit_list is specified, multiple models can be
compared side-by-side in the same plot.
If draw_person_pars = TRUE, simulated datasets incorporate subject-specific effects (random effects).
This requires that monitor_person_pars = TRUE was set during model fitting.
A ggplot object showing density curves of observed and replicated data across time-series variables
(and optionally across individuals).
mlts_posterior_sample for generating replicated data samples.
## Not run: # Set up AR(1) model ar1 <- mlts_model(q = 1, censor_left = -1) # Simulate data under the AR(1) model simData <- mlts_sim(model = ar1, N = 50, TP =100, default = TRUE) # Fit the model fit_AR <- mlts_fit(model = ar1, data = simData$data, id = "ID", ts = "Y1", monitor_person_pars = TRUE) # Run posterior predictive check mlts_pp_check(fit = fit_AR, model_lab = "AR(1)", y_rep_col = "steelblue") ## End(Not run)## Not run: # Set up AR(1) model ar1 <- mlts_model(q = 1, censor_left = -1) # Simulate data under the AR(1) model simData <- mlts_sim(model = ar1, N = 50, TP =100, default = TRUE) # Fit the model fit_AR <- mlts_fit(model = ar1, data = simData$data, id = "ID", ts = "Y1", monitor_person_pars = TRUE) # Run posterior predictive check mlts_pp_check(fit = fit_AR, model_lab = "AR(1)", y_rep_col = "steelblue") ## End(Not run)
Simulate data from mlts model
mlts_sim( model, default = FALSE, N = NULL, N_G = NULL, TP, burn.in = 50, seed = NULL, seed.true = 1, btw.var.sds = NULL, exogenous = NULL )mlts_sim( model, default = FALSE, N = NULL, N_G = NULL, TP, burn.in = 50, seed = NULL, seed.true = 1, btw.var.sds = NULL, exogenous = NULL )
model |
|
default |
logical. If set to |
N |
integer Number of observational units. |
N_G |
vector of integers. Number of observational units per group. |
TP |
integer. Number of measurements per observational unit. |
burn.in |
integer. Length of ‘burn-in’ period. |
seed |
integer. Seed used for data generation. |
seed.true |
integer. Separate seed used for sampling of true population parameters values from plausible ranges for stationary time series. |
btw.var.sds |
named numeric vector. Provide standard deviation(s) for all exogenous
between-level variable(s) specified in |
exogenous |
Matrix of numeric values of exogenous variables with |
A function to generate data from an output of mlts_model.
An object of class "mlts_simdata".
The object is a list containing the following components:
model |
the model object passed to |
data |
a long format |
RE.pars |
a |
# build a simple vector-autoregressive mlts model with two time-series variables var_model <- mlts_model(q = 2) # simulate data from this model with default true values # (true values are randomly drawn from normal distribution) var_data <- mlts_sim( model = var_model, N = 50, TP = 30, # number of units and number of measurements per unit default = TRUE # use default parameter values ) # the data set is stored in .$data head(var_data$data) # individual parameter values are stored in .$RE.pars head(var_data$RE.pars) # if the mltssim-object is used in mlts_fit(), true values # are added to the fitted object fit <- mlts_fit( model = var_model, data = var_data, id = "ID", ts = c("Y1", "Y2"), time = "time" ) # inspect model with true values head(fit$pop.pars.summary)# build a simple vector-autoregressive mlts model with two time-series variables var_model <- mlts_model(q = 2) # simulate data from this model with default true values # (true values are randomly drawn from normal distribution) var_data <- mlts_sim( model = var_model, N = 50, TP = 30, # number of units and number of measurements per unit default = TRUE # use default parameter values ) # the data set is stored in .$data head(var_data$data) # individual parameter values are stored in .$RE.pars head(var_data$RE.pars) # if the mltssim-object is used in mlts_fit(), true values # are added to the fitted object fit <- mlts_fit( model = var_model, data = var_data, id = "ID", ts = c("Y1", "Y2"), time = "time" ) # inspect model with true values head(fit$pop.pars.summary)
Get Standardized Estimates for an mlts Model
mlts_standardized( object, what = c("between", "within", "both"), digits = 3, prob = 0.95, add_cluster_std = FALSE, get_samples = FALSE )mlts_standardized( object, what = c("between", "within", "both"), digits = 3, prob = 0.95, add_cluster_std = FALSE, get_samples = FALSE )
object |
|
what |
character. Get between-level standardized estimates ( |
digits |
Number of digits. Default is 3. |
prob |
A value between 0 and 1 to indicate the width of the credible interval. Default is .95. |
add_cluster_std |
logical. If |
get_samples |
logical. For internal use. |
A list containing between- and within-level standardized parameters.
# build simple vector-autoregressive mlts model for two time-series variables var_model <- mlts_model(q = 2) # fit model with (artificial) dataset ts_data fit <- mlts_fit( model = var_model, data = ts_data, ts = c("Y1", "Y2"), # time-series variables id = "ID", # identifier variable time = "time", # time variable tinterval = 1, # interval for approximation of continuous-time dynamic model, monitor_person_pars = TRUE # person parameters need to be sampled for standardization ) # inspect standardized parameter estimates mlts_standardized(fit)# build simple vector-autoregressive mlts model for two time-series variables var_model <- mlts_model(q = 2) # fit model with (artificial) dataset ts_data fit <- mlts_fit( model = var_model, data = ts_data, ts = c("Y1", "Y2"), # time-series variables id = "ID", # identifier variable time = "time", # time variable tinterval = 1, # interval for approximation of continuous-time dynamic model, monitor_person_pars = TRUE # person parameters need to be sampled for standardization ) # inspect standardized parameter estimates mlts_standardized(fit)
mltsfit
Create a summary of a fitted model with class mltsfit
## S3 method for class 'mltsfit' summary( object, priors = FALSE, se = FALSE, prob = 0.95, bpe = c("mean"), digits = 3, flag_signif = FALSE, ... )## S3 method for class 'mltsfit' summary( object, priors = FALSE, se = FALSE, prob = 0.95, bpe = c("mean"), digits = 3, flag_signif = FALSE, ... )
object |
An object of class |
priors |
Add prior information (default = FALSE). |
se |
Logical. Should the Monte Carlo Standard Error be included
in the summary? Defaults to |
prob |
A value between 0 and 1 to indicate the width of the credible interval. Default is .95. |
bpe |
Bayesian posterior estimate can be either "mean" (the default) or the "median" of the posterior distribution. |
digits |
Number of digits. |
flag_signif |
Add significance flags based on |
... |
Additional arguments affecting the summary produced. |
A summary of model parameters.
# build simple vector-autoregressive mlts model for two time-series variables var_model <- mlts_model(q = 2) # fit model with (artificial) dataset ts_data fit <- mlts_fit( model = var_model, data = ts_data, ts = c("Y1", "Y2"), # time-series variables id = "ID", # identifier variable time = "time", tinterval = 1 # interval for approximation of continuous-time dynamic model, ) # inspect model summary summary(fit)# build simple vector-autoregressive mlts model for two time-series variables var_model <- mlts_model(q = 2) # fit model with (artificial) dataset ts_data fit <- mlts_fit( model = var_model, data = ts_data, ts = c("Y1", "Y2"), # time-series variables id = "ID", # identifier variable time = "time", tinterval = 1 # interval for approximation of continuous-time dynamic model, ) # inspect model summary summary(fit)
Simulated Time-Series Data (from mlts_sim) for two
time-series variables.
ts_datats_data
ts_dataA data frame with 1,100 rows and 4 columns:
Unit identifier
Time point
The two time-series variables