Package {nlpsem}


Type: Package
Title: Nonlinear Longitudinal Process in Structural Equation Modeling
Version: 1.0.0
Description: Provides computational tools for nonlinear longitudinal models, in particular the intrinsically nonlinear models, in four scenarios: (1) univariate longitudinal processes with growth factors, with or without covariates including time-invariant covariates (TICs) and time-varying covariates (TVCs); (2) multivariate longitudinal processes that facilitate the assessment of associations and directional relationships between multiple longitudinal variables; (3) multiple-group models for scenarios (1) and (2) to evaluate differences among manifested groups, and (4) longitudinal mixture models for scenarios (1) and (2), with an assumption that trajectories are from multiple latent classes. Data can also be simulated from these models with the generating parameter values attached. The methods implemented are introduced in Liu (2025) <doi:10.3758/s13428-025-02596-4>.
License: GPL (≥ 3)
Encoding: UTF-8
LazyData: true
Depends: R (≥ 4.0.0), OpenMx (≥ 2.21.8)
Imports: ggplot2, dplyr, tidyr, stringr, Matrix, nnet, methods, grDevices, graphics, stats, utils, rlang (≥ 0.4.0)
RoxygenNote: 7.3.3
URL: https://github.com/Veronica0206/nlpsem
BugReports: https://github.com/Veronica0206/nlpsem/issues
Suggests: testthat (≥ 3.2.0), knitr, rmarkdown
VignetteBuilder: knitr
Config/testthat/edition: 3
NeedsCompilation: no
Packaged: 2026-11-01 23:57:40 UTC; runner
Author: Jin Liu ORCID iD [aut, cre]
Maintainer: Jin Liu <Veronica.Liu0206@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-02 03:30:02 UTC

S4 Class for estimated factor scores and their standard errors.

Description

S4 Class for the output structure for the getIndFS() function.

Slots

scores_est

A matrix of estimated factor scores.

scores_se

A matrix of standard errors of estimated factor scores.


S4 Class for kappa statistic with confidence interval and judgment.

Description

S4 Class for the output structure for the getLatentKappa() function.

Slots

kappa_value

A character vector for the kappa statistic with a confidence interval.

judgment

A character vector for the judgement for agreement.


S4 Generic for summarizing an optimized MxModel.

Description

Generic function for printing model summary of MxModel object.

Usage

ModelSummary(object)

Arguments

object

An object of the appropriate class.

Value

Invisibly returns the summary of the MxModel object. Called primarily for its side effect of printing the model summary.

Examples

load(system.file("extdata", "getLGCM_examples.RData", package = "nlpsem"))
ModelSummary(Math_LGCM_BLS_r)


S4 Method for summarizing an optimized MxModel.

Description

Method for printing model summary of MxModel object.

Usage

## S4 method for signature 'myMxOutput'
ModelSummary(object)

Arguments

object

An object of class "myMxOutput".

Value

Invisibly returns the summary of the MxModel object. Called primarily for its side effect of printing the model summary.


ECLS-K (2011) Sample Dataset for Demonstration

Description

A sample dataset extracted from the public-use Early Childhood Longitudinal Study, Kindergarten Class of 2010-11 (ECLS-K:2011) collected by the National Center for Education Statistics (NCES). This dataset is NOT a posting of the original data, and it has been processed and formatted for use in demonstration purposes within this package. For access to the original data, please visit the NCES data products page at https://nces.ed.gov/ecls/dataproducts.asp.

Usage

RMS_dat

Format

A data frame with 500 rows and 49 variables:

ID

Identification number.

R1, R2, R3, R4, R5, R6, R7, R8, R9

Reading scores from 9 study waves.

M1, M2, M3, M4, M5, M6, M7, M8, M9

Math scores from 9 study waves.

S2, S3, S4, S5, S6, S7, S8, S9

Science scores from 8 study waves (starting from the second study wave).

T1, T2, T3, T4, T5, T6, T7, T8, T9

Children's age-in-month at 9 study waves.

SEX

Sex of the child.

RACE

Race of the child.

LOCALE

Locale of the child's school.

INCOME

Family income.

SCHOOL_TYPE

Type of the child's school.

Approach_to_Learning

Teacher's rating on the child's approach to learning.

Self_control

Teacher's rating on the child's self-control.

Interpersonal

Teacher's rating on the child's interpersonal skills.

External_prob_Behavior

Teacher's rating on the child's external problem behaviors.

Internal_prob_Behavior

Teacher's rating on the child's internal problem behaviors.

Attention_focus

Teacher's rating on the child's attention focus.

Inhibitory_Ctrl

Teacher's rating on the child's inhibitory control.

EDU

Highest education level between the child's parents.

Details

The ECLS-K:2011 offers a comprehensive and detailed set of information about children's early life experiences, following children's health, development, education, and experiences from kindergarten through fifth grade.

The preparation script excludes incomplete records on selected variables and samples 500 complete cases without replacement using seed 20191029. This teaching sample is not a representative population analysis sample by default. The sample dataset included in this package is used for demonstrating the functionality of the package's functions and it does not include survey weights. In real analysis, the complex survey weights provided by NCES should be utilized appropriately, for instance, as done in R packages such as lavaan.survey or EdSurvey if not using SEM.

Please note that this data must not be used to attempt to identify respondents. For detailed documentation and proper usage of the ECLS-K:2011 data, please refer to the original source at the National Center for Education Statistics (NCES) website: https://nces.ed.gov/.

Source

https://nces.ed.gov/ecls/dataproducts.asp


S4 Class for p values and confidence intervals (when specified).

Description

S4 Class for the output structure for the getEstimateStats() function.

Slots

wald

A data frame for p values and Wald confidence intervals (when specified).

likelihood

A data frame for Likelihood confidence intervals (when specified).

bootstrap

A data frame for Bootstrap confidence intervals (when specified).


S4 Class for displaying figures

Description

S4 Class to hold the figures output from the getFigure function.

Slots

figures

A list of lists containing figures for each specified sub_model and y_model (when applicable).


Inspect Numerical Diagnostics of a Stored Fit

Description

Separates optimizer completion from covariance admissibility, Hessian quality, standard-error availability and mixture component sizes. The function inspects stored results without refitting, changing constraints, or treating an optimizer status of zero as statistical acceptance.

Usage

getDiagnostics(object, tolerance = 1e-08)

Arguments

object

A fitted myMxOutput object or an OpenMx MxModel.

tolerance

Positive finite tolerance below one for symmetry and eigenvalue checks after diagonal scaling. Default is 1e-8.

Details

A fitted result requires a finite stored Minus2LogLikelihood and an optimizer status. Other fit objectives, including weighted least squares, are outside this diagnostic's current scope. For fitted RAM models, checks cover the stored S matrix and its latent disturbance and manifest residual blocks, including jointly fitted children. Cached nlpsem covariance algebras ending in _psi0, _psi_r or _psi_s are also inspected. Scalar-label block algebras are matched to their positions in RAM S. A block joining distinct variable sets is reported separately in cross_covariances: its entries may be negative and it need not be symmetric. Admissibility is checked on the assembled joint RAM S, not on the cross block alone. This structural matching does not infer roles from outcome-name lengths or from the numerical symmetry of a fitted block. Covariance matrices depending on definition variables are not evaluated for individual rows. Other expectation types, missing cached results and unfitted models are marked unavailable.

Eigenvalues are calculated after a diagonal congruence transformation using the square roots of absolute diagonal entries; a zero diagonal uses its row's largest absolute entry (or the smallest positive double for an all-zero row). This permits structurally zero disturbance variances. A negative diagonal is always reported. Scaled eigenvalues below minus tolerance indicate an indefinite matrix; near-zero eigenvalues are reported as near_boundary and require substantive interpretation rather than automatic rejection.

Hessian diagnostics use the stored calculated Hessian, falling back to the stored Hessian, and separately report OpenMx's infoDefinite flag. Positive semidefiniteness is insufficient for an invertible Hessian, so a singular or near-singular Hessian is flagged. Standard errors are checked for completeness, finiteness and positivity for the estimated free parameters. These checks do not establish identification or calibrated uncertainty.

For recognized nlpsem mixture models, component sizes include hard assignment counts and sums of posterior probabilities. Empty hard-assignment classes are flagged; there is no universal acceptable class-size threshold. Multiple starts, likelihood optimality, row-specific implied covariances, interval coverage and statistical model assumptions remain unassessed. Results describe the stored fit; manually changing it can leave cached outputs stale. Refit a modified model before interpreting these diagnostics. Covariance checks assume references resolve within each RAM model; custom cross-model covariance expressions require additional independent checks.

The fitting functions (getLGCM(), getLCSM(), getTVCmodel(), getMGM(), getMediation(), getMGroup() and getMIX()) run these checks on each new fit and return the fit with a warning of class "nlpsem_diagnostics_warning" that lists the issues when there are any, so that a solution with, for example, an indefinite covariance matrix is not reported silently. Missing standard errors are recorded as unavailable and do not raise the warning.

Value

A list with optimizer, a covariance data frame, a cross_covariances data frame recording recognized cross blocks, hessian, standard_errors, component_sizes, issues, repeated_starts, and limitations. Each covariance row identifies its model, matrix and block. The raw and scaled minimum eigenvalues are reported separately. Empty or unsupported checks are explicitly unavailable. issues lists detected problems; an empty list of issues does not certify statistical validity.

See Also

getSpecification, getPosterior

Examples

load(system.file("extdata", "getTVCmodel_examples.RData", package = "nlpsem"))
diagnostics <- getDiagnostics(Math_TVCchgBL_BLS_r)
diagnostics$optimizer
diagnostics$covariance
diagnostics$issues


Calculate p-Values and Confidence Intervals of Parameters for a Fitted Model

Description

This function calculates p-values and confidence intervals (CIs) of parameters for a given model. It supports different types of CIs, including Wald CIs, likelihood-based CIs, bootstrap CIs, or all three. Likelihood-based and bootstrap CIs refit model as returned, on the original scale: a quadratic, negative exponential or Jenss-Bayley model that was fitted on the standardized scale is not standardized again for these refits.

Usage

getEstimateStats(
  model = NULL,
  est_in,
  p_values = TRUE,
  CI = TRUE,
  CI_type = "Wald",
  rep = NA,
  conf.level = 0.95
)

Arguments

model

A fitted mxModel object. Specifically, this should be the mxOutput slot from the result returned by one of the estimation functions provided by this package. The default value is NULL. Providing this parameter is essential when generating likelihood-based and bootstrap confidence intervals (CIs).

est_in

The Estimates slot from the result returned by one of the estimation functions provided by this package, which contains a dataframe with point estimates and standard errors.

p_values

A logical flag indicating whether to calculate p-values. Default is TRUE.

CI

A logical flag indicating whether to compute confidence intervals. Default is TRUE.

CI_type

A string specifying the type of confidence interval to compute. Supported options include "Wald", "likelihood", "bootstrap", or "all". Default is "Wald". An unrecognized value triggers an informative error.

rep

An integer specifying the number of replications for bootstrap. A positive integer must be supplied when CI_type is "bootstrap" or "all". Default is NA.

conf.level

A numeric value representing the confidence level for confidence interval calculation. It applies to Wald, likelihood-based, and bootstrap confidence intervals. Default is 0.95.

Value

An object of class StatsOutput with potential slots:

The content of these slots can be printed using the printTable() method for S4 objects. Numeric estimates, standard errors, and interval endpoints retain full precision; the p-value column is formatted for display. Use unrounded input estimates and standard errors for inference. Saved objects created before version 1.0.0.9003 may contain rounded Estimates; their lost precision cannot be recovered by this function. Bootstrap intervals use only replications with an acceptable OpenMx status and finite parameter estimates. Discarded replications trigger a warning; fewer than two usable replications trigger an error. The bootstrap data frame has a bootstrap_diagnostics attribute recording requested, attempted, successful and discarded counts and status frequencies.

References

See Also

getLGCM, getIndFS, getPosterior

Examples

# Fitted bilinear spline latent growth curve models shipped with the package
load(system.file("extdata", "getLGCM_examples.RData", package = "nlpsem"))
# p values and Wald confidence intervals
stats_wald <- getEstimateStats(est_in = Math_LGCM_TIC_BLS_f@Estimates, CI_type = "Wald")
printTable(stats_wald)
## Not run: 
# Likelihood-based and bootstrap intervals re-optimize the model; this takes several minutes
mxOption(model = NULL, key = "Default optimizer", "SLSQP", reset = FALSE)
getEstimateStats(
  model = Math_LGCM_TIC_BLS_f@mxOutput, est_in = Math_LGCM_TIC_BLS_f@Estimates,
  CI_type = "all", rep = 20
)

## End(Not run)


Generate Visualization for Fitted Model

Description

This function generates visualizations for the output of a fitted model. When a Latent Growth Curve Model (LGCM) is fitted for the longitudinal process, it provides (class-specific) estimated growth status with 95% pointwise confidence intervals. When a Latent Change Score Model (LCSM) is fitted for the longitudinal process, it provides (class-specific) estimated interval-average growth rate with 95% pointwise confidence intervals and change from baseline with 95% pointwise confidence intervals. These visualizations are particularly useful for understanding the results and trajectories of different classes or groups within the model. Intervals use the delta method and the full estimated covariance of the growth parameters, including estimated rates, knots, and covariate-adjusted means. They describe uncertainty in the model-implied mean curve, not prediction intervals or simultaneous confidence bands. Bounds are not truncated to the observed-data range. Intrinsic bilinear-spline curves retain the fitted smoothed loadings at the expansion knot and the mean knot deviation, including their joint uncertainty. For a nonintrinsic bilinear spline, an interval is omitted at the exact estimated knot when the knot has nonzero uncertainty and the two slopes differ, because the derivative is not unique. Multiple-group change-score plots use each group's mean observation times; mixture plots use pooled mean times as a common reference grid. Change curves and their intervals are relative to the first selected observation time on that grid. LCSM plots use the fitted discrete change recurrence, including its midpoint approximation for exponential and Jenss–Bayley curves, rather than the corresponding continuous growth curve. Selecting a subset of fitted waves retains all intervening fitted increments and rebases the change to the first selected wave. Rates are the fitted change between consecutive selected waves divided by their time difference, displayed at the interval's ending time. Nonparametric rate plots show each rate as a horizontal segment across its corresponding interval. Their intervals propagate the joint covariance of these contrasts. Waves may be selected in fitted order or its reverse; arbitrary reorderings and repeated waves are rejected. For two selected waves, the single interval is displayed as a point with a vertical confidence interval. An observed mean is shown as a cross when only one distinct observation time is available for smoothing.

Usage

getFigure(
  model,
  nClass = NULL,
  cluster_TIC = NULL,
  grp_var = NULL,
  sub_Model,
  y_var,
  curveFun,
  y_model = NULL,
  t_var,
  records,
  m_var = NULL,
  x_type = NULL,
  x_var = NULL,
  xstarts,
  xlab = "Time",
  outcome = "Process"
)

Arguments

model

A fitted mxModel object. Specifically, this should be the mxOutput slot from the result returned by one of the estimation functions provided by this package.

nClass

An integer specifying the number of latent classes for the mixture model or manifested classes for multiple group model. Default is NULL, indicating a single-group model.

cluster_TIC

A string or character vector representing the column name(s) for time-invariant covariate(s) indicating cluster formations. Default is NULL, indicating no such time-invariant covariates are present in the model.

grp_var

A string specifying the column that indicates manifested classes when applicable.

sub_Model

A string that specifies the (class-specific) model. Supported sub-models include "LGCM" (for latent growth curve models), "LCSM" (for latent change score models), "TVC" (for latent growth curve models or latent change score models with a time-varying covariate), "MGM" (for multivariate latent growth curve models or latent change score models), and "MED" (for longitudinal mediation models).

y_var

A string or character vector representing the prefix of the column names for the outcome variable(s) at each study wave.

curveFun

A string specifying the functional forms of the growth curve(s). Supported options for y_model = "LGCM" include: "linear" (or "LIN"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), "Jenss-Bayley" (or "JB"), and "bilinear spline" (or "BLS"). Supported options for y_model = "LCSM" include: "nonparametric" (or "NonP"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), and "Jenss-Bayley" (or "JB").

y_model

A string that specifies how to fit longitudinal outcomes. Supported values are "LGCM" and "LCSM". By default, this is NULL as this argument is only required when sub_Model is "TVC" or "MGM".

t_var

A string specifying the prefix of the column names corresponding to the time variable at each study wave. For sub_Model being "MGM" or "MED", t_var should be a character vector where each element corresponds to the time variable prefix for each respective longitudinal process.

records

A numeric vector representing the indices of the study waves. For sub_Model being "MGM" or "MED", records should be a list of numeric vectors, where each vector provides the indices of the observed study waves for each longitudinal process.

m_var

A string that specifies the prefix of the column names corresponding to the mediator variable at each time point. Default is NULL as this argument is only required when sub_Model is "MED".

x_type

A string indicating the type of predictor variable used in the model. Supported values are "baseline" and "longitudinal". Default is NULL as this argument is only required when sub_Model is "MED".

x_var

A string specifying the baseline predictor if x_type = "baseline", or the prefix of the column names corresponding to the predictor variable at each study wave if x_type = "longitudinal". Default is NULL as this argument is only required when sub_Model is "MED".

xstarts

A numeric value to indicate the starting time of the longitudinal process.

xlab

A string representing the time unit (e.g., "Week", "Month", or "Year") for the x-axis. Default is "Time".

outcome

A string or character vector representing the name(s) of the longitudinal process(es) under examination.

Value

An object of class figOutput containing a slot named figures. This slot holds a ggplot object or a list of ggplot objects, each representing a figure for the fitted model. If the figures slot contains a list of ggplot objects, individual figures can be visualized using the show() function.

See Also

getLGCM, getLCSM, getTVCmodel, getMGM, getMediation, getMGroup, getMIX

Examples

# Fitted models shipped with the package
load(system.file("extdata", "getLGCM_examples.RData", package = "nlpsem"))
# Single-group bilinear spline latent growth curve model with time-invariant covariates
Figure1 <- getFigure(
  model = Math_LGCM_TIC_BLS_f@mxOutput, sub_Model = "LGCM", y_var = "M", curveFun = "BLS",
  y_model = "LGCM", t_var = "T", records = 1:9, xstarts = xstarts, xlab = "Month",
  outcome = "Mathematics"
)
show(Figure1)
# Three-class mixture of bilinear spline models
load(system.file("extdata", "getMIX_examples.RData", package = "nlpsem"))
Figure2 <- getFigure(
  model = Math_BLS_LGCM3@mxOutput, nClass = 3, sub_Model = "LGCM", y_var = "M",
  curveFun = "BLS", y_model = "LGCM", t_var = "T", records = 1:9, xstarts = xstarts,
  xlab = "Month", outcome = "Mathematics"
)
show(Figure2)
# Longitudinal mediation model: one figure per process (outcome, mediator)
load(system.file("extdata", "getMediation_examples.RData", package = "nlpsem"))
Figure3 <- getFigure(
  model = Med2_LGCM_BLS@mxOutput, sub_Model = "MED", y_var = "M", m_var = "R",
  x_type = "baseline", x_var = "ex1", curveFun = "BLS", t_var = rep("T", 2),
  records = list(1:9, 1:9), xstarts = xstarts, xlab = "Month",
  outcome = c("Mathematics", "Reading")
)
show(Figure3)

Derive Individual Factor Scores for Each Latent Variable Included in Model

Description

This function computes individual factor scores for each latent variable in a given model. It supports three types of factor scores: maximum likelihood, weighted maximum likelihood, and regression.

Usage

getIndFS(model, FS_type = "Regression")

Arguments

model

A fitted mxModel object. Specifically, this should be the mxOutput slot from the result returned by a single-process or multivariate model with one RAM or LISREL expectation and its own raw data. Multiple-group and mixture parent models are not supported.

FS_type

A string specifying the type of factor scores to compute. Supported options include "ML" (for Maximum Likelihood), "WeightedML" (for Weighted Maximum Likelihood), and "Regression". Default is "Regression".

Details

Before scoring, the observed data stored in the model are reduced to the variables the model actually uses (manifest variables and definition variables), and the model is given a name without spaces or punctuation. Both steps are required by OpenMx::mxFactorScores(): columns that are not part of the model make the "ML" and "WeightedML" scoring runs fail, and the descriptive model names used by this package are not valid identifiers for the scoring model.

Value

An object of class FSOutput with two slots:

The content of these slots can be printed using the printTable() method for S4 objects.

References

See Also

getEstimateStats

Examples

# Fitted bilinear spline model (fixed knot) shipped with the package
load(system.file("extdata", "getLGCM_examples.RData", package = "nlpsem"))

# Regression scores for the 500 persons (individual measurement occasions are definition
# variables, so the scores are computed person by person; about 15 seconds)
FS <- getIndFS(model = Math_LGCM_BLS_r@mxOutput, FS_type = "Regression")
head(FS@scores_est)
# Maximum-likelihood scores re-optimize one model per person
FS_ML <- getIndFS(model = Math_LGCM_BLS_r@mxOutput, FS_type = "ML")
head(FS_ML@scores_est)



Fit a Latent Change Score Model with a Time-invariant Covariate (If Any)

Description

This function fits a latent change score model with or without time-invariant covariates to the provided data. It manages model setup, optimization, and if requested, outputs parameter estimates and standard errors.

Usage

getLCSM(
  dat,
  t_var,
  y_var,
  curveFun,
  intrinsic = TRUE,
  records,
  growth_TIC = NULL,
  starts = NULL,
  res_scale = NULL,
  tries = NULL,
  OKStatus = 0,
  jitterD = "runif",
  loc = 1,
  scale = 0.25,
  paramOut = FALSE,
  names = NULL
)

Arguments

dat

A wide-format data frame, with each row corresponding to a unique ID. It contains the observed variables with repeated measurements and occasions, and time-invariant covariates (TICs) if any.

t_var

A string specifying the prefix of the column names corresponding to the time variable at each study wave.

y_var

A string specifying the prefix of the column names corresponding to the outcome variable at each study wave.

curveFun

A string specifying the functional form of the growth curve. Supported options for latent change score models include: "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), "Jenss-Bayley" (or "JB"), and "nonparametric" (or "NonP").

intrinsic

A logical flag indicating whether to build an intrinsically nonlinear longitudinal model. Default is TRUE.

records

A numeric vector specifying indices of the study waves.

growth_TIC

A string or character vector specifying the column name(s) of time-invariant covariate(s) contributing to the variability of growth factors if any. Default is NULL, indicating no growth TICs are included in the model.

starts

A list containing initial values for the parameters. Default is NULL, indicating no user-specified initial values.

res_scale

An optional numeric value representing the scaling factor for the initial calculation of the residual variance. This value should be between 0 and 1, exclusive. Default is NULL, in which case data-driven residual variance estimation is used. If data-driven estimation fails, a heuristic of 0.1 is applied as fallback.

tries

An integer specifying the number of additional optimization attempts. Default is NULL.

OKStatus

An integer (vector) specifying acceptable status codes for convergence. Default is 0.

jitterD

A string specifying the distribution for jitter. Supported values are: "runif" (uniform distribution), "rnorm" (normal distribution), and "rcauchy" (Cauchy distribution). Default is "runif".

loc

A numeric value representing the location parameter of the jitter distribution. Default is 1.

scale

A numeric value representing the scale parameter of the jitter distribution. Default is 0.25.

paramOut

A logical flag indicating whether to output the parameter estimates and standard errors. Default is FALSE.

names

A character vector specifying parameter names. Default is NULL, in which case meaningful names are automatically generated based on the model configuration.

Details

New fits retain their resolved model specification and fitting provenance. A new fit whose getDiagnostics reports issues (for example a nonzero optimizer status or an indefinite covariance matrix) is returned with a warning that lists them. Use getSpecification to inspect it; standard summary(), coef(), logLik() and plot() methods are available.

Value

An object of class myMxOutput. Depending on the paramOut argument, the object may contain the following slots:

Standardized fitting

Models with a quadratic, negative exponential or Jenss-Bayley functional form are fitted to standardized data and converted back to the original units. Each outcome is centred at the mean and divided by the standard deviation of its first recorded occasion, a time-varying covariate is divided by its first-occasion standard deviation, and time is divided by the mean of its last recorded occasion; time-invariant covariates are not changed. The model starts from the same starting values, mapped exactly to the standardized scale, and is optimized with the same optimizer and retry settings. The estimates (means, variances, covariances, residual variances, path coefficients, growth ratios and, with a time-varying covariate, its effects), the Hessian, the parameter covariance matrix, the standard errors and the -2 log-likelihood are converted back exactly, so the result is the same model in the original units; only the numerical conditioning of the optimization differs. getSpecification() records the centres, scales and condition numbers under fitting$standardization. Set options(nlpsem.standardize = FALSE) to fit on the original scale.

Approximations

A latent change score model takes the change over each interval as the rate of change at the midpoint of the interval times the length of the interval. This is exact for the quadratic and nonparametric forms. For the negative exponential and Jenss-Bayley forms, the midpoint approximation introduces an integration error whose size depends on curvature and interval length. With intrinsic = TRUE, a first-order Taylor expansion around the mean growth ratio introduces an additional approximation. In an illustrative benchmark using getSimData() defaults (one data set of 5,000 persons per model, ten yearly occasions), the estimated mean of eta1 (negative exponential) or eta2 (Jenss-Bayley) was up to about 2.5% too large in magnitude for fixed-ratio models. In the random-ratio cases, the Taylor and midpoint errors moved those estimated means in opposite directions; the estimated covariance of eta2 and the ratio in the Jenss-Bayley case was about 40% above its generating value. These are observed estimation errors in individual generated data sets, not replicated estimates of bias, coverage rates or general error bounds.

References

See Also

getLGCM, getTVCmodel, getFigure

Examples

mxOption(model = NULL, key = "Default optimizer", "CSOLNP", reset = FALSE)
# Load the ECLS-K (2011) sample and re-baseline the measurement occasions (in years)
data("RMS_dat")
RMS_dat0 <- RMS_dat
baseT <- RMS_dat0$T1
for (j in 1:9) RMS_dat0[[paste0("T", j)]] <- (RMS_dat0[[paste0("T", j)]] - baseT) / 12


# Nonparametric latent change score model for reading development
NonP_LCSM <- getLCSM(
  dat = RMS_dat0, t_var = "T", y_var = "R", curveFun = "nonparametric",
  intrinsic = FALSE, records = 1:9, paramOut = TRUE
)
printTable(NonP_LCSM)



Fit a Latent Growth Curve Model with Time-invariant Covariate (If Any)

Description

This function fits a latent growth curve model with or without time-invariant covariates to the provided data. It manages model setup, optimization, and if requested, outputs parameter estimates and standard errors.

Usage

getLGCM(
  dat,
  t_var,
  y_var,
  curveFun,
  intrinsic = TRUE,
  records,
  growth_TIC = NULL,
  starts = NULL,
  res_scale = NULL,
  tries = NULL,
  OKStatus = 0,
  jitterD = "runif",
  loc = 1,
  scale = 0.25,
  paramOut = FALSE,
  names = NULL
)

Arguments

dat

A wide-format data frame, with each row corresponding to a unique ID. It contains the observed variables with repeated measurements and occasions, and time-invariant covariates (TICs) if any.

t_var

A string specifying the prefix of the column names corresponding to the time variable at each study wave.

y_var

A string specifying the prefix of the column names corresponding to the outcome variable at each study wave.

curveFun

A string specifying the functional form of the growth curve. Supported options for latent growth curve models are: "linear" (or "LIN"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), "Jenss-Bayley" (or "JB"), and "bilinear spline" (or "BLS").

intrinsic

A logical flag indicating whether to build an intrinsically nonlinear longitudinal model. Default is TRUE.

records

A numeric vector specifying indices of the study waves.

growth_TIC

A string or character vector specifying the column name(s) of time-invariant covariate(s) contributing to the variability of growth factors if any. Default is NULL, indicating no growth TICs are included in the model.

starts

A list containing initial values for the parameters. Default is NULL, indicating no user-specified initial values.

res_scale

An optional numeric value representing the scaling factor for the initial calculation of the residual variance. This value should be between 0 and 1, exclusive. Default is NULL, in which case data-driven residual variance estimation is used. If data-driven estimation fails, a heuristic of 0.1 is applied as fallback.

tries

An integer specifying the number of additional optimization attempts. Default is NULL.

OKStatus

An integer (vector) specifying acceptable status codes for convergence. Default is 0.

jitterD

A string specifying the distribution for jitter. Supported values are: "runif" (uniform distribution), "rnorm" (normal distribution), and "rcauchy" (Cauchy distribution). Default is "runif".

loc

A numeric value representing the location parameter of the jitter distribution. Default is 1.

scale

A numeric value representing the scale parameter of the jitter distribution. Default is 0.25.

paramOut

A logical flag indicating whether to output the parameter estimates and standard errors. Default is FALSE.

names

A character vector specifying parameter names. Default is NULL, in which case meaningful names are automatically generated based on the model configuration.

Details

New fits retain their resolved model specification and fitting provenance. A new fit whose getDiagnostics reports issues (for example a nonzero optimizer status or an indefinite covariance matrix) is returned with a warning that lists them. Use getSpecification to inspect it; standard summary(), coef(), logLik() and plot() methods are available.

Value

An object of class myMxOutput. Depending on the paramOut argument, the object may contain the following slots:

Standardized fitting

Models with a quadratic, negative exponential or Jenss-Bayley functional form are fitted to standardized data and converted back to the original units. Each outcome is centred at the mean and divided by the standard deviation of its first recorded occasion, a time-varying covariate is divided by its first-occasion standard deviation, and time is divided by the mean of its last recorded occasion; time-invariant covariates are not changed. The model starts from the same starting values, mapped exactly to the standardized scale, and is optimized with the same optimizer and retry settings. The estimates (means, variances, covariances, residual variances, path coefficients, growth ratios and, with a time-varying covariate, its effects), the Hessian, the parameter covariance matrix, the standard errors and the -2 log-likelihood are converted back exactly, so the result is the same model in the original units; only the numerical conditioning of the optimization differs. getSpecification() records the centres, scales and condition numbers under fitting$standardization. Set options(nlpsem.standardize = FALSE) to fit on the original scale.

References

See Also

getLCSM, getTVCmodel, getFigure

Examples

mxOption(model = NULL, key = "Default optimizer", "CSOLNP", reset = FALSE)
# Load the ECLS-K (2011) sample and re-baseline the measurement occasions (in months)
data("RMS_dat")
RMS_dat0 <- RMS_dat
baseT <- RMS_dat0$T1
for (j in 1:9) RMS_dat0[[paste0("T", j)]] <- RMS_dat0[[paste0("T", j)]] - baseT
# Standardized time-invariant covariates
RMS_dat0$ex1 <- scale(RMS_dat0$Approach_to_Learning)
RMS_dat0$ex2 <- scale(RMS_dat0$Attention_focus)


# Bilinear spline latent growth curve model with a fixed knot
BLS_LGCM_r <- getLGCM(
  dat = RMS_dat0, t_var = "T", y_var = "M", curveFun = "bilinear spline",
  intrinsic = FALSE, records = 1:9, paramOut = TRUE
)
printTable(BLS_LGCM_r)

## Not run: 
# Intrinsically nonlinear model (random knot) with time-invariant covariates and 20 extra
# optimization attempts; this takes several minutes
set.seed(20191029)
BLS_LGCM.TIC_f <- getLGCM(
  dat = RMS_dat0, t_var = "T", y_var = "M", curveFun = "bilinear spline",
  intrinsic = TRUE, records = 1:9, growth_TIC = c("ex1", "ex2"),
  tries = 20, paramOut = TRUE
)
printTable(BLS_LGCM.TIC_f)

## End(Not run)


Perform Bootstrap Likelihood Ratio Test for Comparing Full and Reduced Models

Description

Wraps OpenMx model comparison for a fitted full model and a corresponding reduced model, with optional parametric bootstrapping. A returned p-value is meaningful only when the comparison satisfies the required assumptions.

Usage

getLRT(full, reduced, boot = FALSE, rep = NA)

Arguments

full

A fitted mxModel object for the full model. Specifically, this should be the mxOutput slot from the result returned by one of the estimation functions provided by this package.

reduced

A fitted mxModel object for the reduced model. Specifically, this should be the mxOutput slot from the result returned by one of the estimation functions provided by this package.

boot

A logical flag indicating whether to perform bootstrapping for the comparison. Default is FALSE.

rep

An integer specifying the number of bootstrap replications if boot is TRUE. Default is NA.

Details

Both models must use the same observations and observed variables, and the reduced model must be nested in the full model. Neither this wrapper nor OpenMx establishes mathematical nesting automatically. Inspect getDiagnostics() and check solution stability before interpreting results. The ordinary chi-square reference requires the usual likelihood regularity conditions; boundary parameters, unidentified parameters, and latent class enumeration can violate these conditions.

In particular, random-knot and fixed-knot bilinear spline fits use different smooth/absolute-value loading formulas, and latent covariances are not generally constrained to be positive semidefinite. Their automatic comparison is not a validated significance test for a random-knot effect. Establish the null model, admissible parameter space and calibration for the intended analysis.

boot = TRUE delegates to OpenMx::mxCompare(). It does not repair invalid models or non-nesting. Use enough successful replications to control Monte Carlo error, and inspect bootstrap fitting behavior. A reported zero bootstrap p-value is bounded by the simulation resolution, not evidence of a probability exactly equal to zero.

Value

A data frame containing the number of free parameters, estimated likelihood (-2ll), degrees of freedom, differences in log-likelihood and degrees of freedom, p-values, AIC, and BIC for both the full and reduced models.

See Also

getSummary

Examples

# Historical comparison output: inspect the assumptions in Details before
# interpreting the p-value for these nonlinear models.
load(system.file("extdata", "getLGCM_examples.RData", package = "nlpsem"))
comparison <- getLRT(full = Math_LGCM_BLS_f@mxOutput,
                     reduced = Math_LGCM_BLS_r@mxOutput)
comparison[, c("# of Free Param", "-2loglik", "AIC", "BIC")]


Compute Latent Kappa Coefficient for Agreement between Two Latent Label Sets

Description

This function calculates the latent kappa, a measure of agreement between two sets of latent categorical labels. It also computes the confidence interval and provides a qualitative interpretation of the agreement level. Categories are matched by their label values, independently of factor-level order. Latent class numbers have no intrinsic correspondence across models: align their meanings explicitly before calling this function. The function does not permute classes to maximize agreement.

Usage

getLatentKappa(label1, label2, conf.level = 0.95)

Arguments

label1

A factor vector representing the first set of latent categorical labels.

label2

A factor vector representing the second set of latent categorical labels.

conf.level

A numeric value representing the confidence level for the confidence interval of the kappa statistic. The default value is 0.95.

Details

The confidence interval uses the multinomial delta-method variance for paired categorical labels, including uncertainty in their empirical marginal frequencies. It treats subjects as independent and the supplied labels as observed; uncertainty from fitting latent class models or assigning classes is not included. The requested confidence level is retained as an attribute for printing. Older objects without this attribute are printed without assuming a confidence level.

Value

An object of class KappaOutput with the following slots:

The content of these slots can be printed using the printTable() method for S4 objects.

References

See Also

getPosterior, getMIX

Examples

# Class memberships from two fitted three-class mixtures shipped with the package
load(system.file("extdata", "getMIX_examples.RData", package = "nlpsem"))
label1 <- getPosterior(model = Math_BLS_LGCM3@mxOutput, nClass = 3)@membership
label2 <- getPosterior(
  model = RM_BLS_PLGCM3@mxOutput, nClass = 3, cluster_TIC = c("gx1", "gx2")
)@membership
kappa <- getLatentKappa(label1 = label1, label2 = label2)
printTable(kappa)


Fit a Multivariate Latent Growth Curve Model or Multivariate Latent Change Score Model

Description

This function fits a multivariate latent growth curve model or a multivariate latent change score model with the provided data. It manages model setup, optimization, and if requested, outputs parameter estimates and standard errors.

Usage

getMGM(
  dat,
  t_var,
  y_var,
  curveFun,
  intrinsic = TRUE,
  records,
  y_model,
  starts = NULL,
  res_scale = NULL,
  res_cor = NULL,
  tries = NULL,
  OKStatus = 0,
  jitterD = "runif",
  loc = 1,
  scale = 0.25,
  paramOut = FALSE,
  names = NULL
)

Arguments

dat

A wide-format data frame, with each row corresponding to a unique ID. It contains the observed variables with repeated measurements and occasions for multiple longitudinal outcomes.

t_var

A vector of strings, with each element representing the prefix for column names related to the time variable for the corresponding outcome variable at each study wave.

y_var

A vector of strings, with each element representing the prefix for column names corresponding to a particular outcome variable at each study wave. The parameters shared by two outcomes are labelled by joining their prefixes ("Y" and "Z" give "YZ"), so prefixes for which a joined pair equals a prefix or another pair (such as "A", "B" and "AB") are rejected; with y_model = "LCSM", the prefixes must also differ in more than letter case.

curveFun

A string specifying the functional forms of the growth curve(s). Supported options for y_model = "LGCM" include: "linear" (or "LIN"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), "Jenss-Bayley" (or "JB"), and "bilinear spline" (or "BLS"). Supported options for y_model = "LCSM" include: "nonparametric" (or "NonP"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), and "Jenss-Bayley" (or "JB").

intrinsic

A logical flag indicating whether to build an intrinsically nonlinear longitudinal model. Default is TRUE.

records

A list of numeric vectors, with each vector specifying the indices of the observed study waves for the corresponding outcome variable. Every pair of outcomes must share at least one record ID to estimate its residual covariance. Residual pairs are matched by record ID, independently of the order of the selected columns.

y_model

A string specifying how to fit the longitudinal outcome. Supported values are "LGCM" and "LCSM".

starts

A list containing initial values for the parameters. Default is NULL, indicating no user-specified initial values.

res_scale

An optional numeric vector with each element representing the scaling factor for the initial calculation of the residual variance. These values should be between 0 and 1, exclusive. Default is NULL, in which case data-driven residual variance estimation is used. If data-driven estimation fails, a heuristic of 0.1 is applied as fallback.

res_cor

An optional numeric value or vector for user-specified residual correlation between any two longitudinal outcomes to calculate the corresponding initial value. Default is NULL, in which case data-driven residual correlation estimation is used. If data-driven estimation fails, a heuristic of 0.3 is applied as fallback.

tries

An integer specifying the number of additional optimization attempts. Default is NULL.

OKStatus

An integer (vector) specifying acceptable status codes for convergence. Default is 0.

jitterD

A string specifying the distribution for jitter. Supported values are: "runif" (uniform distribution), "rnorm" (normal distribution), and "rcauchy" (Cauchy distribution). Default is "runif".

loc

A numeric value representing the location parameter of the jitter distribution. Default is 1.

scale

A numeric value representing the scale parameter of the jitter distribution. Default is 0.25.

paramOut

A logical flag indicating whether to output the parameter estimates and standard errors. Default is FALSE.

names

A character vector specifying parameter names. Default is NULL, in which case meaningful names are automatically generated based on the model configuration.

Details

New fits retain their resolved model specification and fitting provenance. A new fit whose getDiagnostics reports issues (for example a nonzero optimizer status or an indefinite covariance matrix) is returned with a warning that lists them. Use getSpecification to inspect it; standard summary(), coef(), logLik() and plot() methods are available.

Value

An object of class myMxOutput. Depending on the paramOut argument, the object may contain the following slots:

Standardized fitting

Models with a quadratic, negative exponential or Jenss-Bayley functional form are fitted to standardized data and converted back to the original units. Each outcome is centred at the mean and divided by the standard deviation of its first recorded occasion, a time-varying covariate is divided by its first-occasion standard deviation, and time is divided by the mean of its last recorded occasion; time-invariant covariates are not changed. The model starts from the same starting values, mapped exactly to the standardized scale, and is optimized with the same optimizer and retry settings. The estimates (means, variances, covariances, residual variances, path coefficients, growth ratios and, with a time-varying covariate, its effects), the Hessian, the parameter covariance matrix, the standard errors and the -2 log-likelihood are converted back exactly, so the result is the same model in the original units; only the numerical conditioning of the optimization differs. getSpecification() records the centres, scales and condition numbers under fitting$standardization. Set options(nlpsem.standardize = FALSE) to fit on the original scale.

References

See Also

getLGCM, getMGroup, getMIX, getFigure

Examples

mxOption(model = NULL, key = "Default optimizer", "CSOLNP", reset = FALSE)
# Load the ECLS-K (2011) sample and re-baseline the measurement occasions (in months)
data("RMS_dat")
RMS_dat0 <- RMS_dat
baseT <- RMS_dat0$T1
for (j in 1:9) RMS_dat0[[paste0("T", j)]] <- RMS_dat0[[paste0("T", j)]] - baseT


# Linear multivariate latent growth curve model for reading and mathematics
LIN_PLGCM_f <- getMGM(
  dat = RMS_dat0, t_var = c("T", "T"), y_var = c("R", "M"), curveFun = "LIN",
  intrinsic = FALSE, records = list(1:9, 1:9), y_model = "LGCM", paramOut = TRUE
)
printTable(LIN_PLGCM_f)

## Not run: 
# Bilinear spline multivariate model with random knots and 20 extra optimization
# attempts; this takes several minutes
set.seed(20191029)
BLS_PLGCM_f <- getMGM(
  dat = RMS_dat0, t_var = c("T", "T"), y_var = c("R", "M"), curveFun = "BLS",
  intrinsic = TRUE, records = list(1:9, 1:9), y_model = "LGCM",
  tries = 20, paramOut = TRUE
)
printTable(BLS_PLGCM_f)

## End(Not run)


Fit a Longitudinal Multiple Group Model

Description

This function fits a longitudinal multiple group model based on the specified sub-model. Supported submodels include:

For the first three submodels, time-invariant covariates are allowed.

Usage

getMGroup(
  dat,
  grp_var,
  sub_Model,
  t_var,
  records,
  y_var,
  curveFun,
  intrinsic = NULL,
  y_model = NULL,
  m_var = NULL,
  x_type = NULL,
  x_var = NULL,
  TVC = NULL,
  decompose = NULL,
  growth_TIC = NULL,
  starts = NULL,
  res_scale = NULL,
  res_cor = NULL,
  tries = NULL,
  OKStatus = 0,
  jitterD = "runif",
  loc = 1,
  scale = 0.25,
  paramOut = FALSE,
  names = NULL
)

Arguments

dat

A wide-format data frame, with each row corresponding to a unique ID. It contains the observed variables with repeated measurements and occasions for each longitudinal process, time-invariant covariates (TICs) if any, and a variable that indicates manifested group.

grp_var

A string specifying the column that indicates manifested classes. Any coding (numeric, character, or factor) is accepted: the distinct non-missing values are sorted and relabelled 1, 2, ... in that order for estimation and in the output, and a message reports the mapping when the original codes differ. Rows with a missing group value are removed with a warning.

sub_Model

A string that specifies the sub-model for manifested classes. Supported sub-models include "LGCM" (for latent growth curve models), "LCSM" (for latent change score models), "TVC" (for latent growth curve models or latent change score models with a time-varying covariate), "MGM" (for multivariate latent growth curve models or latent change score models), and "MED" (for longitudinal mediation models).

t_var

A string specifying the prefix of the column names corresponding to the time variable for each study wave. This applies when sub_Model is "LGCM", "LCSM" or "TVC". For sub_Model being "MGM" or "MED", t_var should be a string vector where each element corresponds to the time variable prefix for each respective longitudinal process.

records

A numeric vector denoting the indices of the observed study waves. This applies when sub_Model is "LGCM", "LCSM" or "TVC". For sub_Model being "MGM" or "MED", records should be a list of numeric vectors, where each vector provides the indices of the observed study waves for each longitudinal process.

y_var

A string defining the prefix of the column names corresponding to the outcome variable for each study wave. This is applicable when sub_Model is not "MGM". For sub_Model being "MGM", y_var should be a string vector where each element corresponds to the prefix of the column names for each outcome variable across the study waves; see getMGM for the prefixes that are rejected because their labels would be ambiguous.

curveFun

A string specifying the functional forms of the growth curve(s). Supported options for y_model = "LGCM" include: "linear" (or "LIN"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), "Jenss-Bayley" (or "JB"), and "bilinear spline" (or "BLS"). Supported options for y_model = "LCSM" include: "nonparametric" (or "NonP"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), and "Jenss-Bayley" (or "JB").

intrinsic

A logical flag indicating whether to build an intrinsically nonlinear longitudinal model. By default, this is NULL, as it is unnecessary when sub_Model is "MED".

y_model

A string that specifies how to fit longitudinal outcomes. Supported values are "LGCM" and "LCSM". By default, this is NULL as this argument is only required when sub_Model is "TVC" or "MGM".

m_var

A string that specifies the prefix of the column names corresponding to the mediator variable at each study wave. By default, this is NULL as this argument is only required when sub_Model is "MED".

x_type

A string indicating the type of predictor variable used in the model. Supported values are "baseline" and "longitudinal". By default, this is NULL as this argument is only required when sub_Model is "MED".

x_var

A string specifying the baseline predictor if x_type = "baseline", or the prefix of the column names corresponding to the predictor variable at each study wave if x_type = "longitudinal". By default, this is NULL as this argument is only required when sub_Model is "MED".

TVC

A string that specifies the prefix of the column names corresponding to the time-varying covariate at each time point. By default, this is NULL as this argument is only required when sub_Model is "TVC".

decompose

An integer specifying the decomposition option for temporal states. Supported values include 0 (no decomposition), 1 (decomposition with interval-specific slopes as temporal states), 2 (decomposition with interval- specific changes as temporal states), and 3 (decomposition with change-from-baseline as temporal states). By default, this is NULL as this argument is only required when sub_Model is "TVC".

growth_TIC

A string or character vector of column names of time-invariant covariate(s) accounting for the variability of growth factors if any. Default is NULL, indicating no growth TICs present in the model.

starts

A list containing initial values for the parameters. Default is NULL, indicating no user-specified initial values.

res_scale

An optional list where each element is a (vector of) numeric scaling factor(s) for residual variance to calculate the corresponding initial value for a latent class, between 0 and 1 exclusive. Default is NULL, in which case data-driven residual variance estimation is used. If data-driven estimation fails, a heuristic of 0.1 is applied as fallback.

res_cor

An optional list where each element is a (vector of) numeric initial value(s) for residual correlation in each class. Applicable when the sub_Model is "TVC" (when decompose != 0), "MGM", or "MED". Default is NULL, in which case the residual correlations of "TVC" and "MGM" models are estimated from the per-person curve residuals (with 0.3 as fallback) and those of "MED" models start at 0.3.

tries

An integer specifying the number of additional optimization attempts. Default is NULL.

OKStatus

An integer (vector) specifying acceptable status codes for convergence. Default is 0.

jitterD

A string specifying the distribution for jitter. Supported values are: "runif" (uniform distribution), "rnorm" (normal distribution), and "rcauchy" (Cauchy distribution). Default is "runif".

loc

A numeric value representing the location parameter of the jitter distribution. Default is 1.

scale

A numeric value representing the scale parameter of the jitter distribution. Default is 0.25.

paramOut

A logical flag indicating whether to output the parameter estimates and standard errors. Default is FALSE.

names

A character vector specifying parameter names. Default is NULL, in which case meaningful names are automatically generated based on the model configuration.

Details

New fits retain their resolved model specification and fitting provenance. A new fit whose getDiagnostics reports issues (for example a nonzero optimizer status or an indefinite covariance matrix) is returned with a warning that lists them. For multivariate submodels, every outcome pair must share at least one record ID; see getMGM. Use getSpecification to inspect it; standard summary(), coef(), logLik() and plot() methods are available.

Value

An object of class myMxOutput. Depending on the paramOut argument, the object may contain the following slots:

Standardized fitting

Latent growth curve, latent change score, TVC and multivariate sub-models with a quadratic, negative exponential or Jenss-Bayley functional form are fitted to standardized data and converted back to the original units. Each outcome is centred at the mean and divided by the standard deviation of its first recorded occasion, pooled within the groups, a time-varying covariate is divided by its first-occasion standard deviation (also pooled within the groups), and time is divided by the mean of its last recorded occasion; time-invariant covariates are not changed. The model starts from the same starting values, mapped exactly to the standardized scale, and is optimized with the same optimizer and retry settings. The estimates (means, variances, covariances, residual variances, path coefficients, growth ratios and, with a time-varying covariate, its effects), the Hessian, the parameter covariance matrix, the standard errors and the -2 log-likelihood are converted back exactly, so the result is the same model in the original units; only the numerical conditioning of the optimization differs. getSpecification() records the centres, scales and condition numbers under fitting$standardization. Set options(nlpsem.standardize = FALSE) to fit on the original scale.

References

See Also

getLGCM, getLCSM, getMIX, getFigure

Examples

mxOption(model = NULL, key = "Default optimizer", "CSOLNP", reset = FALSE)
# Load the ECLS-K (2011) sample and re-baseline the measurement occasions (in months)
data("RMS_dat")
RMS_dat0 <- RMS_dat
baseT <- RMS_dat0$T1
for (j in 1:9) RMS_dat0[[paste0("T", j)]] <- RMS_dat0[[paste0("T", j)]] - baseT
# Standardized time-invariant covariates
RMS_dat0$ex1 <- scale(RMS_dat0$Approach_to_Learning)
RMS_dat0$ex2 <- scale(RMS_dat0$Attention_focus)


# Multiple-group bilinear spline model with a fixed knot, groups defined by sex
MGroup_BLS_LGCM_r <- getMGroup(
  dat = RMS_dat0, grp_var = "SEX", sub_Model = "LGCM", y_var = "M", t_var = "T",
  records = 1:9, curveFun = "BLS", intrinsic = FALSE, paramOut = TRUE
)
printTable(MGroup_BLS_LGCM_r)

## Not run: 
# Random knot with time-invariant covariates and 10 extra optimization attempts;
# this takes several minutes
set.seed(20191029)
MGroup_BLS_LGCM.TIC_f <- getMGroup(
  dat = RMS_dat0, grp_var = "SEX", sub_Model = "LGCM", y_var = "M", t_var = "T",
  records = 1:9, curveFun = "BLS", intrinsic = TRUE,
  growth_TIC = c("ex1", "ex2"), tries = 10, paramOut = TRUE
)
printTable(MGroup_BLS_LGCM.TIC_f)

## End(Not run)


Fit a Longitudinal Mixture Model

Description

This function fits a longitudinal mixture model based on the specified sub-model. Supported submodels include:

Time-invariant covariates are allowed for the first three submodels.

Usage

getMIX(
  dat,
  prop_starts,
  sub_Model,
  cluster_TIC = NULL,
  t_var,
  records,
  y_var,
  curveFun,
  intrinsic = NULL,
  y_model = NULL,
  m_var = NULL,
  x_type = NULL,
  x_var = NULL,
  TVC = NULL,
  decompose = NULL,
  growth_TIC = NULL,
  starts = NULL,
  res_scale = NULL,
  res_cor = NULL,
  tries = NULL,
  OKStatus = 0,
  jitterD = "runif",
  loc = 1,
  scale = 0.25,
  paramOut = FALSE,
  names = NULL
)

Arguments

dat

A wide-format data frame, with each row corresponding to a unique ID. It contains the observed variables with repeated measurements and occasions for each longitudinal process, and time-invariant covariates (TICs) if any.

prop_starts

A numeric vector of user-specified initial component proportions of latent classes.

sub_Model

A string that specifies the sub-model for latent classes. Supported sub-models include "LGCM" (for latent growth curve models), "LCSM" (for latent change score models), "TVC" (for latent growth curve models or latent change score models with a time-varying covariate), "MGM" (for multivariate latent growth curve models or latent change score models), and "MED" (for longitudinal mediation models).

cluster_TIC

A string or character vector representing the column name(s) for time-invariant covariate(s) indicating cluster formations. Default is NULL, indicating no such time-invariant covariates are present in the model.

t_var

A string specifying the prefix of the column names corresponding to the time variable for each study wave. This applies when sub_Model is "LGCM", "LCSM" or "TVC". For sub_Model being "MGM" or "MED", t_var should be a string vector where each element corresponds to the time variable prefix for each respective longitudinal process.

records

A numeric vector denoting the indices of the observed study waves. This applies when sub_Model is "LGCM", "LCSM" or "TVC". For sub_Model being "MGM" or "MED", records should be a list of numeric vectors, where each vector provides the indices of the observed study waves for each longitudinal process.

y_var

A string defining the prefix of the column names corresponding to the outcome variable for each study wave. This is applicable when sub_Model is not "MGM". For sub_Model being "MGM", y_var should be a string vector where each element corresponds to the prefix of the column names for each outcome variable across the study waves; see getMGM for the prefixes that are rejected because their labels would be ambiguous.

curveFun

A string specifying the functional forms of the growth curve(s). Supported options for y_model = "LGCM" include: "linear" (or "LIN"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), "Jenss-Bayley" (or "JB"), and "bilinear spline" (or "BLS"). Supported options for y_model = "LCSM" include: "nonparametric" (or "NonP"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), and "Jenss-Bayley" (or "JB").

intrinsic

A logical flag indicating whether to build an intrinsically nonlinear longitudinal model. By default, this is NULL as it is unnecessary when sub_Model is "MED".

y_model

A string that specifies how to fit longitudinal outcomes. Supported values are "LGCM" and "LCSM". By default, this is NULL as this argument is only required when sub_Model is "TVC" or "MGM".

m_var

A string that specifies the prefix of the column names corresponding to the mediator variable at each study wave. By default, this is NULL as this argument is only required when sub_Model is "MED".

x_type

A string indicating the type of predictor variable used in the model. Supported values are "baseline" and "longitudinal". By default, this is NULL as this argument is only required when sub_Model is "MED".

x_var

A string specifying the baseline predictor if x_type = "baseline", or the prefix of the column names corresponding to the predictor variable at each study wave if x_type = "longitudinal". By default, this is NULL as this argument is only required when sub_Model is "MED".

TVC

A string that specifies the prefix of the column names corresponding to the time-varying covariate at each time point. By default, this is NULL as this argument is only required when sub_Model is "TVC".

decompose

An integer specifying the decomposition option for temporal states. Supported values include 0 (no decomposition), 1 (decomposition with interval-specific slopes as temporal states), 2 (decomposition with interval- specific changes as temporal states), and 3 (decomposition with change-from-baseline as temporal states). By default, this is NULL as this argument is only required when sub_Model is "TVC".

growth_TIC

A string or character vector of column names of time-invariant covariate(s) accounting for the variability of growth factors if any. Default is NULL, indicating no growth TICs present in the model.

starts

A list containing initial values for the parameters. Default is NULL, indicating no user-specified initial values.

res_scale

An optional list where each element is a (vector of) numeric scaling factor(s) for residual variance to calculate the corresponding initial value for a latent class, between 0 and 1 exclusive. Default is NULL, in which case data-driven residual variance estimation is used. If data-driven estimation fails, a heuristic of 0.1 is applied as fallback.

res_cor

An optional list where each element is a (vector of) numeric initial value(s) for residual correlation in each class. Applicable when the sub_Model is "TVC" (when decompose != 0), "MGM", or "MED". Default is NULL, in which case the residual correlations of "TVC" and "MGM" models are estimated from the per-person curve residuals (with 0.3 as fallback) and those of "MED" models start at 0.3.

tries

An integer specifying the number of additional optimization attempts. Default is NULL.

OKStatus

An integer (vector) specifying acceptable status codes for convergence. Default is 0.

jitterD

A string specifying the distribution for jitter. Supported values are: "runif" (uniform distribution), "rnorm" (normal distribution), and "rcauchy" (Cauchy distribution). Default is "runif".

loc

A numeric value representing the location parameter of the jitter distribution. Default is 1.

scale

A numeric value representing the scale parameter of the jitter distribution. Default is 0.25.

paramOut

A logical flag indicating whether to output the parameter estimates and standard errors. Default is FALSE.

names

A character vector specifying parameter names. Default is NULL, in which case meaningful names are automatically generated based on the model configuration.

Details

New fits retain their resolved model specification and fitting provenance. A new fit whose getDiagnostics reports issues (for example a nonzero optimizer status or an indefinite covariance matrix) is returned with a warning that lists them. For multivariate submodels, every outcome pair must share at least one record ID; see getMGM. Use getSpecification to inspect it; standard summary(), coef(), logLik() and plot() methods are available.

Value

An object of class myMxOutput. Depending on the paramOut argument, the object may contain the following slots:

Standardized fitting

Latent growth curve, latent change score, TVC and multivariate sub-models with a quadratic, negative exponential or Jenss-Bayley functional form are fitted to standardized data and converted back to the original units. Each outcome is centred at the mean and divided by the standard deviation of its first recorded occasion, pooled within the provisional classes that the automatic starting values are computed from (with user-supplied starts, the overall standard deviation), a time-varying covariate is divided by its first-occasion standard deviation (pooled in the same way), and time is divided by the mean of its last recorded occasion; time-invariant covariates are not changed. The model starts from the same starting values, mapped exactly to the standardized scale, and is optimized with the same optimizer and retry settings. The estimates (means, variances, covariances, residual variances, path coefficients, growth ratios and, with a time-varying covariate, its effects), the Hessian, the parameter covariance matrix, the standard errors and the -2 log-likelihood are converted back exactly, so the result is the same model in the original units; only the numerical conditioning of the optimization differs. getSpecification() records the centres, scales and condition numbers under fitting$standardization. Set options(nlpsem.standardize = FALSE) to fit on the original scale.

References

See Also

getLGCM, getLCSM, getMGroup, getFigure

Examples

mxOption(model = NULL, key = "Default optimizer", "CSOLNP", reset = FALSE)
# Load the ECLS-K (2011) sample and re-baseline the measurement occasions (in months)
data("RMS_dat")
RMS_dat0 <- RMS_dat
baseT <- RMS_dat0$T1
for (j in 1:9) RMS_dat0[[paste0("T", j)]] <- RMS_dat0[[paste0("T", j)]] - baseT
# Standardized time-invariant covariates
RMS_dat0$ex1 <- scale(RMS_dat0$Approach_to_Learning)
RMS_dat0$ex2 <- scale(RMS_dat0$Attention_focus)
# Standardized cluster-forming covariates
RMS_dat0$gx1 <- scale(RMS_dat0$INCOME)
RMS_dat0$gx2 <- scale(RMS_dat0$EDU)


# Two-class mixture of linear latent growth curve models
set.seed(20191029)
MIX_LIN_LGCM <- getMIX(
  dat = RMS_dat0, prop_starts = c(0.45, 0.55), sub_Model = "LGCM",
  y_var = "M", t_var = "T", records = 1:9, curveFun = "LIN", intrinsic = FALSE,
  paramOut = TRUE
)
printTable(MIX_LIN_LGCM)

## Not run: 
# Three-class bilinear spline mixture with cluster-forming and growth covariates and
# 10 extra optimization attempts; this takes several minutes
set.seed(20191029)
MIX_BLS_LGCM.TIC_r <- getMIX(
  dat = RMS_dat0, prop_starts = c(0.33, 0.34, 0.33), sub_Model = "LGCM",
  cluster_TIC = c("gx1", "gx2"), y_var = "M", t_var = "T", records = 1:9,
  curveFun = "BLS", intrinsic = FALSE, growth_TIC = c("ex1", "ex2"),
  tries = 10, paramOut = TRUE
)
printTable(MIX_BLS_LGCM.TIC_r)

## End(Not run)


Fit a Longitudinal Mediation Model

Description

This function fits a longitudinal mediation model to the provided data. It manages model setup, optimization, and if requested, outputs parameter estimates and standard errors.

Usage

getMediation(
  dat,
  t_var,
  y_var,
  m_var,
  x_type,
  x_var,
  curveFun,
  records,
  starts = NULL,
  res_scale = NULL,
  res_cor = NULL,
  tries = NULL,
  OKStatus = 0,
  jitterD = "runif",
  loc = 1,
  scale = 0.25,
  paramOut = FALSE,
  names = NULL
)

Arguments

dat

A wide-format data frame, with each row corresponding to a unique ID. It contains the observed variables with repeated measurements and occasions for multiple longitudinal processes and a baseline predictor when applicable.

t_var

A vector of strings, with each element representing the prefix for column names related to the time variable for the corresponding longitudinal variable at each study wave.

y_var

A string specifying the prefix of the column names corresponding to the outcome variable at each study wave.

m_var

A string specifying the prefix of the column names corresponding to the mediator variable at each study wave.

x_type

A string indicating the type of predictor variable used in the model. Supported values are "baseline" and "longitudinal".

x_var

A string specifying the baseline predictor if x_type = "baseline", or the prefix of the column names corresponding to the predictor variable at each study wave if x_type = "longitudinal".

curveFun

A string specifying the functional form of the growth curve. Supported options include: "linear" (or "LIN"), and "bilinear spline" (or "BLS").

records

A list of numeric vectors, with each vector specifying the indices of the observed study waves for the corresponding longitudinal variable.

starts

A list containing initial values for the parameters. Default is NULL, indicating no user-specified initial values.

res_scale

An optional numeric vector with each element representing the scaling factor for the initial calculation of the residual variance. These values should be between 0 and 1, exclusive. Default is NULL, in which case data-driven residual variance estimation is used. If data-driven estimation fails, a heuristic of 0.1 is applied as fallback. Supply two values for a baseline predictor (outcome, mediator), or three for a longitudinal predictor (outcome, mediator, predictor). Each scale multiplies the corresponding individual intercept variance for a linear model, or knot-level variance for a bilinear spline model.

res_cor

An optional numeric value or vector for user-specified residual correlation between any two longitudinal processes to calculate the corresponding initial value. Default is NULL, in which case the residual correlations start at 0.3.

tries

An integer specifying the number of additional optimization attempts. Default is NULL.

OKStatus

An integer (vector) specifying acceptable status codes for convergence. Default is 0.

jitterD

A string specifying the distribution for jitter. Supported values are: "runif" (uniform distribution), "rnorm" (normal distribution), and "rcauchy" (Cauchy distribution). Default is "runif".

loc

A numeric value representing the location parameter of the jitter distribution. Default is 1.

scale

A numeric value representing the scale parameter of the jitter distribution. Default is 0.25.

paramOut

A logical flag indicating whether to output the parameter estimates and standard errors. Default is FALSE.

names

A character vector specifying parameter names. Default is NULL, in which case meaningful names are automatically generated based on the model configuration.

Details

New fits retain their resolved model specification and fitting provenance. A new fit whose getDiagnostics reports issues (for example a nonzero optimizer status or an indefinite covariance matrix) is returned with a warning that lists them. Use getSpecification to inspect it; standard summary(), coef(), logLik() and plot() methods are available.

Value

An object of class myMxOutput. Depending on the paramOut argument, the object may contain the following slots:

References

See Also

getLGCM, getTVCmodel, getFigure

Examples

mxOption(model = NULL, key = "Default optimizer", "CSOLNP", reset = FALSE)
# Load the ECLS-K (2011) sample and re-baseline the measurement occasions (in months)
data("RMS_dat")
RMS_dat0 <- RMS_dat
baseT <- RMS_dat0$T1
for (j in 1:9) RMS_dat0[[paste0("T", j)]] <- RMS_dat0[[paste0("T", j)]] - baseT
# Standardized baseline predictor
RMS_dat0$ex1 <- scale(RMS_dat0$Approach_to_Learning)


# Baseline predictor, linear functional form
Med2_LGCM_LIN <- getMediation(
  dat = RMS_dat0, t_var = rep("T", 2), y_var = "M", m_var = "R", x_type = "baseline",
  x_var = "ex1", curveFun = "LIN", records = list(1:9, 1:9), paramOut = TRUE
)
printTable(Med2_LGCM_LIN)

## Not run: 
# Longitudinal predictor, bilinear spline functional form, 10 extra optimization
# attempts; this takes several minutes
set.seed(20191029)
Med3_LGCM_BLS <- getMediation(
  dat = RMS_dat0, t_var = rep("T", 3), y_var = "S", m_var = "M", x_type = "longitudinal",
  x_var = "R", curveFun = "bilinear spline", records = list(2:9, 1:9, 1:9),
  tries = 10, paramOut = TRUE
)
printTable(Med3_LGCM_BLS)

## End(Not run)


Compute Posterior Probabilities, Cluster Assignments, and Model Entropy for a Longitudinal Mixture Model

Description

This function computes posterior probabilities, cluster assignments, and model entropy for a given mixture model with a predefined number of classes. If the true labels are available, it can also compute the model accuracy.

Usage

getPosterior(model, nClass, label = FALSE, cluster_TIC = NULL)

Arguments

model

A fitted mxModel object. Specifically, this should be the mxOutput slot from the output of getMIX().

nClass

A positive integer equal to the number of latent classes in the fitted model.

label

A logical value indicating whether the data contains true labels, which are often available in a simulated data set. Default is FALSE.

cluster_TIC

A string or character vector representing the column name(s) for time-invariant covariate(s) indicating cluster formations. Default is NULL, which recovers the fitted cluster covariates from the model when present. An explicit vector must match the fitted covariates in their original order.

Details

Probabilities are normalized in log space to avoid overflow or underflow from class weights. Nonfinite or negative component likelihoods, and observations with zero likelihood in every class, produce an informative error. Entropy is numeric NA for a one-class model. With label = TRUE, the observed class labels must already use the fitted class numbering; labels are not permuted to maximize accuracy.

Value

An object of class postOutput. Depending on the label argument, the object may contain the following slots:

The content of these slots can be printed using the printTable() method for S4 objects.

References

See Also

getMIX, getLatentKappa

Examples

# Fitted mixture models shipped with the package
load(system.file("extdata", "getMIX_examples.RData", package = "nlpsem"))
# Three-class bilinear spline mixture without cluster-forming covariates
post1 <- getPosterior(model = Math_BLS_LGCM3@mxOutput, nClass = 3)
head(post1@prob)
post1@entropy
# Three-class bivariate mixture with cluster-forming covariates
post2 <- getPosterior(
  model = RM_BLS_PLGCM3@mxOutput, nClass = 3, cluster_TIC = c("gx1", "gx2")
)
table(post2@membership)


Simulate Longitudinal Data from the Models of the Package

Description

This function generates wide-format longitudinal data in which each person's repeated measures follow a latent growth curve, optionally with time-invariant covariates (TICs), a time-varying covariate (TVC), several outcomes, a mediation structure, and several latent classes. The same data can be fitted with a latent growth curve model or a latent change score model (getLGCM() or getLCSM(), or y_model in getTVCmodel(), getMGM(), getMGroup() and getMIX()), and mediation data with getMediation(). The generating parameter values are attached to the data under the names used in Estimates. Identical names do not imply identical parameter definitions: the quadratic, negative exponential and Jenss–Bayley growth curves have time-zero intercepts, whereas a change score model's intercept is the level at the first fitted occasion. See Truth and time origin below before comparing a fit with the attached values.

Usage

getSimData(
  n = 500,
  sub_Model = "LGCM",
  curveFun,
  intrinsic = FALSE,
  nT = 10,
  times = NULL,
  jitter = 0.25,
  decompose = NULL,
  x_type = NULL,
  params = NULL,
  prop = NULL,
  cluster = NULL,
  growth_TIC = NULL,
  cluster_TIC = NULL,
  y_var = NULL,
  t_var = "T",
  TVC = "TVC",
  m_var = "M",
  x_var = "X",
  seed = NULL
)

Arguments

n

An integer: the number of persons. Default is 500.

sub_Model

A string: "LGCM" (one outcome), "TVC" (an outcome with a time-varying covariate), "MGM" (several outcomes) or "MED" (longitudinal mediation). Default is "LGCM".

curveFun

A string specifying the functional form of the growth curves: "linear" (or "LIN"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), "Jenss-Bayley" (or "JB"), "bilinear spline" (or "BLS") or "nonparametric" (or "NonP"); for sub_Model = "MED", "linear" or "bilinear spline". A latent growth curve model fits all but the nonparametric form, and a latent change score model fits the quadratic, negative exponential, Jenss-Bayley and nonparametric forms.

intrinsic

A logical flag: whether the growth ratio (negative exponential and Jenss-Bayley) or the knot (bilinear spline) varies between persons. Not used for sub_Model = "MED", whose knots are the same for everyone. Default is FALSE.

nT

An integer: the number of measurement occasions. Default is 10.

times

A numeric vector of the nT planned occasions. Default is 0, 1, ..., nT - 1.

jitter

A non-negative number: each person's interior occasions are drawn uniformly within jitter of the planned ones (individually varying measurement occasions); the first and the last occasions are the planned ones. Default is 0.25.

decompose

For sub_Model = "TVC": 0 (the TVC enters directly), 1 (through its interval-specific slopes), 2 (its interval-specific changes) or 3 (its change from baseline).

x_type

For sub_Model = "MED": "baseline" or "longitudinal" predictor.

params

A list of parameters for one class, or a list of such lists, one per latent class. See Details. Default is NULL: one class with the settings of the package's simulation studies.

prop

A numeric vector of class proportions for several classes without cluster TICs. Default is NULL (equal proportions).

cluster

A list for several classes whose membership depends on cluster TICs: mean and cov of the cluster TICs, and beta, a matrix of multinomial-logit coefficients with one row per class (the first row zeros, for the reference class) and one column for the intercept and each TIC. Default is NULL.

growth_TIC

A character vector of column names for the growth TICs ("LGCM" and "TVC"). Default is "ex1", "ex2", ... when params has growth-TIC effects.

cluster_TIC

A character vector of column names for the cluster TICs. Default is "gx1", "gx2", ... when cluster is given.

y_var

The prefix of the outcome columns; for sub_Model = "MGM", one prefix per process, with the restrictions of getMGM. Defaults are "Y" and, for "MGM", c("Y", "Z").

t_var

The prefix of the occasion columns, shared by all processes. Default is "T".

TVC

The prefix of the TVC columns. Default is "TVC".

m_var, x_var

The prefixes of the mediator and predictor columns for sub_Model = "MED" (a baseline predictor is the single column x_var). Defaults are "M" and "X".

seed

An integer seed for reproducible data, or NULL. The random number generator state of the session is restored afterwards. Default is NULL.

Details

Growth factors, TICs and the baseline of a TVC or of a mediation predictor are drawn from multivariate normal distributions, each person's repeated measures follow the functional form at their own occasions, and normal residuals are added (correlated between processes at the same occasion). Each trajectory is the exact growth curve at the person's own growth factors. A latent change score model uses an initial level and rates of change; its parameterization and approximation need to be considered when fitting these data. The nonparametric form is a growth curve whose slope in each interval is eta1 times the interval's relative rate.

Two approximations in the fitting functions can affect recovery of the generating values. A model with a random growth ratio or knot uses a first-order Taylor expansion around its mean. A latent change score model approximates each interval's change by its midpoint rate times its length. The latter is exact for quadratic and nonparametric curves, but not for negative exponential and Jenss-Bayley curves; its error shrinks with shorter intervals or less curvature.

In one generated data set of 5,000 persons per configuration, using the default parameters and ten yearly occasions, the observed errors in growth-factor means were about 1% for models using the Taylor expansion alone. For a negative exponential TVC model with decompose = 1 or 3, the TVC effect was 5% to 10% above its generating value and the mean of eta1 or of the ratio up to 3% below. The latent change score fits had errors up to about 2.5% in the magnitude of the mean of eta1 (negative exponential) or eta2 (Jenss-Bayley); the random-ratio Jenss-Bayley fit's covariance of eta2 and the ratio was about 40% above its generating value. Matched-data comparisons using the fitting approximations reduced these discrepancies. These percentages describe those particular samples, not a replicated estimate of bias, a bound on error, or an assessment of interval coverage. The reproducible examples are in ‘data-raw/approximation-bias’ in the source repository.

The elements of a class list of params are:

"LGCM"

mean: a named numeric vector of the means of the growth factors: eta0 (intercept), eta1 (slope; for the negative exponential, the change to the asymptote; for the bilinear spline, the slope before the knot; for the nonparametric form, the slope of the first interval), eta2 (quadratic coefficient; for the Jenss-Bayley, the coefficient of the exponential term; for the bilinear spline, the slope after the knot) and gamma (growth ratio or knot), as the form requires; cov: the covariance matrix of the growth factors that vary between persons (in the order above), not explained by the growth TICs; residual: the residual variance; rel_rate: for the nonparametric form, the relative rates of the nT - 1 intervals, the first 1; tic_mean, tic_cov, beta: for growth TICs, their means and covariance matrix, and their effects on the growth factors that vary between persons (one row per growth factor, one column per TIC).

"MGM"

mean: a list of mean vectors as above, one per process; cov: the covariance matrix of the growth factors that vary between persons, process by process; residual: the covariance matrix of the residuals of the processes at the same occasion; rel_rate: for the nonparametric form, a list of relative rates, one per process.

"TVC"

For the outcome, the elements of a latent growth curve or change score model as above, and kappa, the effect of the TVC. With decompose = 0, tvc: a list with the mean and var of the TVC at each occasion. With decompose = 1, 2 or 3, the TVC is a nonparametric latent change score process: tvc is a list with its mean (eta0, eta1), cov, rel_rate and residual; beta_tvc: the effects of the TVC's latent baseline on the outcome's growth factors that vary between persons; res_cov: the covariance of the TVC and outcome residuals at the same occasion; with growth TICs, cov_bl: their covariances with the TVC's latent baseline. The outcome's mean holds marginal means.

"MED"

x: the predictor, list(mean, var) at baseline or a growth process list(mean, cov); m, y: the mediator and outcome processes, list(mean, cov) (marginal means, and covariances not explained by the predictor and mediator); beta_xm, beta_xy: the effects of the predictor (or of its growth factors) on the mediator's and outcome's growth factors, and beta_my: of the mediator's growth factors on the outcome's (one row per receiving growth factor; a growth factor affects only itself and later ones); residual: the covariance matrix of the residuals of the (predictor,) mediator and outcome at the same occasion. The growth factors are eta0 and eta1 for the linear form, and eta1 (slope before the knot), etar (status at the knot), eta2 (slope after the knot) and the knot gamma for the bilinear spline.

Value

A data frame with columns id, the repeated measures, the occasions t_var1, ..., the TICs and, for several classes, class. Its attribute "truth" holds the generating parameter values without changing their time origin, named as in the Estimates of the matching fitting function, or of getMIX() for several classes (with the class weights as log odds p2, ... against the first class, or as cluster-TIC coefficients beta20, ...); derived quantities (rates and changes of a latent change score model, mediation and total effects) are not included. For quadratic and nonparametric curves, "truth_lcsm" holds the corresponding parameter targets with growth factors anchored at the first generated occasion. It is NULL for other curves. Attribute "truth_info" identifies the generating intercept reference, first occasion, reference records, and the availability and limits of "truth_lcsm". Attribute "growth_factors" holds each person's generating growth factors, and attribute "settings" the arguments.

Truth and time origin

The "truth" attribute always retains the generating parameterization. For quadratic, negative exponential and Jenss–Bayley curves, direct comparisons with same-named change score parameters require the first fitted occasion to be zero for every person, in addition to the approximation qualifications above. The nonparametric curve is already anchored at its first generated occasion. Bilinear-spline growth curves use the first segment's time-zero intercept; bilinear-spline mediation uses status at the process's knot. Valid nonzero-time growth-curve simulation is supported.

For a quadratic curve beginning at t_0, the change score initial factor is \eta_{0,L} = \eta_0 + t_0\eta_1 + t_0^2\eta_2; the other factors retain their definitions. The "truth_lcsm" attribute applies this exact linear transformation to means, disturbance covariances, covariate effects and conditional intercepts, including cross-process covariances and each class's parameters. For example, the default quadratic curve starting at time 5 has initial mean 125 and variance 166.25, whereas "truth" retains the time-zero values 50 and 25. For nonparametric curves, "truth_lcsm" equals "truth".

These targets refer to all generated records, starting at times[1]; they are not automatically rebased when a fit selects a later baseline. A later jittered baseline can require a different transformation for each person. In TVC models the transformed targets describe the outcome growth factors and their covariate effects, and do not establish equivalence between the full TVC-augmented growth curve and a change score recurrence. For negative exponential and Jenss–Bayley curves, "truth_lcsm" is not supplied: midpoint integration and, with a random ratio, nonlinear distribution changes require further qualifications. No first-order transformation is presented as an exact recovery target.

Examples

dat <- getSimData(n = 200, curveFun = "QUAD", seed = 20261027)
head(dat[, 1:6])
attr(dat, "truth")
shifted <- getSimData(n = 30, curveFun = "QUAD", times = 5:14, jitter = 0, seed = 1)
attr(shifted, "truth")[c("mueta0", "psi00")]
attr(shifted, "truth_lcsm")[c("mueta0", "psi00")]

fit <- getLGCM(dat = dat, t_var = "T", y_var = "Y", curveFun = "QUAD", intrinsic = FALSE,
               records = 1:10, paramOut = TRUE)
truth <- attr(dat, "truth")
cbind(estimate = fit@Estimates$Estimate[match(names(truth), fit@Estimates$Name)], truth)

bivariate <- getSimData(n = 200, sub_Model = "MGM", curveFun = "LIN", seed = 1)
names(attr(bivariate, "truth"))


Inspect the Specification and Provenance of a Fitted Model

Description

Returns the resolved specification, fitting settings and provenance recorded by the estimation functions. No caller environment or duplicate data frame is retained. The original S4 slots remain unchanged, so saved models from earlier versions remain readable.

Usage

getSpecification(object)

Arguments

object

An object of class myMxOutput returned by an estimation function.

Details

The specification contains resolved model arguments, with canonical curve names. The recorded call uses .data and, when explicitly supplied, .starts placeholders; it is a provenance record, not an automatically replayable call. The fitting section contains the resolved initial values, optimizer, thread count, retry settings, RNG kind and the pre-initialization RNG state if one existed. Recording metadata neither sets a seed nor creates an RNG state. Unused argument expressions are not evaluated; their fields are NULL and their names appear in fitting$unevaluated_arguments. Literal unused defaults may be recorded. Reproducibility also depends on the data, software versions, optimizer and numerical platform.

The data section records original row count/names, retained and dropped row indices, and, for manifest groups, the original label-to-code mapping and original row indices in each group. Raw observations remain in object@mxOutput. Diagnostics report the optimizer status without reclassifying a nonconverged fit as successful. Modifying the underlying OpenMx object afterwards does not update this stored provenance snapshot.

Value

A list containing schema_version, call, function_name, specification, fitting, data, versions, and diagnostics, or NULL for older objects without saved metadata.

See Also

getLGCM, getMGroup, getMIX

Examples

# Historical objects remain valid and return NULL when metadata was not recorded.
load(system.file("extdata", "getLGCM_examples.RData", package = "nlpsem"))
getSpecification(Math_LGCM_BLS_f)


Summarize Model Fit Statistics for Fitted Models

Description

This function summarizes the model fit statistics for a list of fitted models. The summary includes the number of parameters, estimated likelihood (-2ll), AIC, BIC, and other relevant statistics.

Usage

getSummary(model_list, HetModels = FALSE)

Arguments

model_list

A list of fitted mxModel objects. Specifically, each element of the list should be the mxOutput slot from the result returned by one of the estimation functions provided by this package.

HetModels

A logical flag indicating whether a mixture model or a multiple group model is included in the list. If set to TRUE, the function can also be used for the enumeration process, allowing the determination of the optimal number of latent classes based on model fit statistics such as BIC. The default value is FALSE.

Details

Residual columns are combined by name, with NA where a model does not contain that parameter. For heterogeneous models, each class has one proportion column regardless of the number of longitudinal outcomes. Mixture proportions count maximum-posterior assignments; multiple-group proportions count observations. A summary table does not establish that its models are statistically comparable: compare information criteria only for appropriate models fitted to the same data and observed variables.

Value

A data frame summarizing model fit statistics (number of parameters, estimated likelihood, AIC, BIC, etc.) for each model. A plain data.frame is returned for both HetModels = TRUE and HetModels = FALSE.

See Also

getLGCM, getMIX, getMGroup

Examples

# Fitted models shipped with the package: one-, two- and three-class bilinear spline models
load(system.file("extdata", "getMIX_examples.RData", package = "nlpsem"))
# Single model
getSummary(model_list = list(Math_BLS_LGCM1@mxOutput), HetModels = FALSE)
# Enumeration of latent classes
getSummary(
  model_list = list(Math_BLS_LGCM1@mxOutput, Math_BLS_LGCM2@mxOutput, Math_BLS_LGCM3@mxOutput),
  HetModels = TRUE
)


Fit a Latent Growth Curve Model or Latent Change Score Model with Time-varying and Time-invariant Covariates

Description

This function fits a latent growth curve model or latent change score model with a time-varying covariate and potential time-invariant covariates to the provided data. It manages model setup, optimization, and if requested, outputs parameter estimates and standard errors.

Usage

getTVCmodel(
  dat,
  t_var,
  y_var,
  curveFun,
  intrinsic = TRUE,
  records,
  y_model,
  TVC,
  decompose,
  growth_TIC = NULL,
  starts = NULL,
  res_scale = NULL,
  res_cor = NULL,
  tries = NULL,
  OKStatus = 0,
  jitterD = "runif",
  loc = 1,
  scale = 0.25,
  paramOut = FALSE,
  names = NULL
)

Arguments

dat

A wide-format data frame, with each row corresponding to a unique ID. It contains the observed variables with repeated measurements (for the longitudinal outcome and time-varying covariates), occasions, and time-invariant covariates (TICs) if any.

t_var

A string specifying the prefix of the column names corresponding to the time variable at each study wave.

y_var

A string specifying the prefix of the column names corresponding to the outcome variable at each study wave.

curveFun

A string specifying the functional form of the growth curve. Supported options for y_model = "LGCM" include: "linear" (or "LIN"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), "Jenss-Bayley" (or "JB"), and "bilinear spline" (or "BLS"). Supported options for y_model = "LCSM" include: "nonparametric" (or "NonP"), "quadratic" (or "QUAD"), "negative exponential" (or "EXP"), and "Jenss-Bayley" (or "JB").

intrinsic

A logical flag indicating whether to build an intrinsically nonlinear longitudinal model. Default is TRUE.

records

A numeric vector specifying the indices of the observed study waves.

y_model

A string specifying how to fit the longitudinal outcome. Supported values are "LGCM" and "LCSM".

TVC

A string specifying the prefix of the column names corresponding to the time-varying covariate at each study wave.

decompose

An integer specifying the decomposition option for temporal states. Supported values include 0 (no decomposition), 1 (decomposition with interval-specific slopes as temporal states), 2 (decomposition with interval- specific changes as temporal states), and 3 (decomposition with change-from-baseline as temporal states).

growth_TIC

A string or character vector specifying the column name(s) of time-invariant covariate(s) that account for the variability of growth factors, if any. Default is NULL, indicating no growth TICs present in the model.

starts

A list containing initial values for the parameters. Default is NULL, indicating no user-specified initial values.

res_scale

An optional numeric value or numeric vector. For a model with decompose = 0, it is a numeric value representing the scaling factor used to calculate the initial value for the residual variance of the longitudinal outcome. In cases where decompose != 0, it is a numeric vector of scaling factors used to calculate the initial values for the residual variance of both the longitudinal outcome and the time-varying covariate. Default is NULL, in which case data-driven residual variance estimation is used. If data-driven estimation fails, a heuristic of 0.1 is applied as fallback.

res_cor

An optional numeric value. When decompose != 0, this represents the user-specified residual correlation between the longitudinal outcome and the time-varying covariate, which is used to calculate the corresponding initial value. If decompose = 0, this should be NULL. Default is NULL, in which case data-driven residual correlation estimation is used when decompose != 0. If data-driven estimation fails, a heuristic of 0.3 is applied as fallback.

tries

An integer specifying the number of additional optimization attempts. Default is NULL.

OKStatus

An integer (vector) specifying acceptable status codes for convergence. Default is 0.

jitterD

A string specifying the distribution for jitter. Supported values are: "runif" (uniform distribution), "rnorm" (normal distribution), and "rcauchy" (Cauchy distribution). Default is "runif".

loc

A numeric value representing the location parameter of the jitter distribution. Default is 1.

scale

A numeric value representing the scale parameter of the jitter distribution. Default is 0.25.

paramOut

A logical flag indicating whether to output the parameter estimates and standard errors. Default is FALSE.

names

A character vector specifying parameter names. Default is NULL, in which case meaningful names are automatically generated based on the model configuration.

Details

New fits retain their resolved model specification and fitting provenance. A new fit whose getDiagnostics reports issues (for example a nonzero optimizer status or an indefinite covariance matrix) is returned with a warning that lists them. Use getSpecification to inspect it; standard summary(), coef(), logLik() and plot() methods are available.

Value

An object of class myMxOutput. Depending on the paramOut argument, the object may contain the following slots:

Standardized fitting

Models with a quadratic, negative exponential or Jenss-Bayley functional form are fitted to standardized data and converted back to the original units. Each outcome is centred at the mean and divided by the standard deviation of its first recorded occasion, a time-varying covariate is divided by its first-occasion standard deviation, and time is divided by the mean of its last recorded occasion; time-invariant covariates are not changed. The model starts from the same starting values, mapped exactly to the standardized scale, and is optimized with the same optimizer and retry settings. The estimates (means, variances, covariances, residual variances, path coefficients, growth ratios and, with a time-varying covariate, its effects), the Hessian, the parameter covariance matrix, the standard errors and the -2 log-likelihood are converted back exactly, so the result is the same model in the original units; only the numerical conditioning of the optimization differs. getSpecification() records the centres, scales and condition numbers under fitting$standardization. Set options(nlpsem.standardize = FALSE) to fit on the original scale.

Approximations

With intrinsic = TRUE, the model is fitted through a first-order Taylor expansion of the growth curve around the mean growth ratio or knot. When the expected change of the TVC over time has a similar shape to the growth curve of the outcome, the estimated TVC effect can absorb part of this approximation error. In an illustrative benchmark using getSimData() defaults and a negative exponential curve (one data set of 5,000 persons per model), the estimated TVC effect was 5% to 10% above its generating value and the estimated mean of eta1 or of the ratio was up to 3% below it with decompose = 1 or 3. These are observed estimation errors in individual generated data sets, not replicated estimates of bias, coverage rates or general error bounds. A fixed ratio (intrinsic = FALSE) removes the random-ratio Taylor approximation; it does not eliminate other sources of estimation error. With y_model = "LCSM", the midpoint approximation described in getLCSM also applies.

References

See Also

getLGCM, getLCSM, getFigure

Examples

mxOption(model = NULL, key = "Default optimizer", "CSOLNP", reset = FALSE)
# Load the ECLS-K (2011) sample and re-baseline the measurement occasions (in years)
data("RMS_dat")
RMS_dat0 <- RMS_dat
baseT <- RMS_dat0$T1
for (j in 1:9) RMS_dat0[[paste0("T", j)]] <- (RMS_dat0[[paste0("T", j)]] - baseT) / 12
# Standardized time-invariant covariates
RMS_dat0$ex1 <- scale(RMS_dat0$Approach_to_Learning)
RMS_dat0$ex2 <- scale(RMS_dat0$Attention_focus)
# Standardize the time-varying covariate (reading) by its baseline distribution
BL_mean <- mean(RMS_dat0$R1)
BL_sd <- sd(RMS_dat0$R1)
for (j in 1:9) RMS_dat0[[paste0("Rs", j)]] <- (RMS_dat0[[paste0("R", j)]] - BL_mean) / BL_sd


# Linear latent growth curve model with the time-varying covariate in its original form
LIN_TVC_LGCM <- getTVCmodel(
  dat = RMS_dat0, t_var = "T", y_var = "M", curveFun = "LIN", intrinsic = FALSE,
  records = 1:9, y_model = "LGCM", TVC = "Rs", decompose = 0, paramOut = TRUE
)
printTable(LIN_TVC_LGCM)

## Not run: 
# Negative exponential model with a random ratio, a decomposed time-varying covariate
# (interval-specific slopes) and time-invariant covariates; this takes several minutes
set.seed(20191029)
EXP_TVCslp_LGCM3.f <- getTVCmodel(
  dat = RMS_dat0, t_var = "T", y_var = "M", curveFun = "EXP", intrinsic = TRUE,
  records = 1:9, y_model = "LGCM", TVC = "Rs", decompose = 1,
  growth_TIC = c("ex1", "ex2"), tries = 20, paramOut = TRUE
)
printTable(EXP_TVCslp_LGCM3.f)

## End(Not run)


S4 Class for optimized MxModel and point estimates with standard errors (when applicable)

Description

S4 Class for the output structure for estimate functions.

Slots

mxOutput

An object of class "MxModel".

Estimates

A data frame of estimates.


S4 Class for posterior probabilities, membership, entropy, and accuracy (when applicable)

Description

S4 Class for the output structure for the getPosterior() function.

Slots

prob

A matrix of posterior probabilities.

membership

A numeric vector for membership.

entropy

A numeric value for entropy.

accuracy

A numeric value for accuracy.


S4 Generic for displaying output in a table format.

Description

Generic function for printing output as tables.

Usage

printTable(object)

Arguments

object

An object of the appropriate class.

Value

Called primarily for its side effect of printing formatted output. Returns the object invisibly.

Examples

load(system.file("extdata", "getLGCM_examples.RData", package = "nlpsem"))
printTable(Math_LGCM_TIC_BLS_f)


S4 Method for printing estimated factor scores and their standard errors

Description

Method for printing estimated factor scores and their standard errors.

Usage

## S4 method for signature 'FSOutput'
printTable(object)

Arguments

object

An object of class "FSOutput".

Value

Called for its side effect of printing factor scores and their standard errors. Returns the object invisibly.


S4 Method for printing kappa statistic with a confidence interval and judgement for agreement.

Description

Method for printing kappa statistic with a confidence interval and judgement for agreement.

Usage

## S4 method for signature 'KappaOutput'
printTable(object)

Arguments

object

An object of class "KappaOutput".

Value

Called for its side effect of printing kappa statistic with confidence interval and agreement judgment. Returns the object invisibly.


S4 Method for printing p values and confidence intervals (when applicable)

Description

Method for printing p values and confidence intervals.

Usage

## S4 method for signature 'StatsOutput'
printTable(object)

Arguments

object

An object of class "StatsOutput".

Value

Called for its side effect of printing p values and confidence intervals. Returns the object invisibly.


S4 Method for printing point estimates with standard errors

Description

Method for printing point estimates and standard errors.

Usage

## S4 method for signature 'myMxOutput'
printTable(object)

Arguments

object

An object of class "myMxOutput".

Value

Called for its side effect of printing point estimates and standard errors. Returns the object invisibly.


S4 Method for printing posterior probabilities, membership, entropy, and accuracy.

Description

Method for printing posterior probabilities, membership, entropy, and accuracy.

Usage

## S4 method for signature 'postOutput'
printTable(object)

Arguments

object

An object of class "postOutput".

Value

Called for its side effect of printing posterior probabilities, membership, entropy, and accuracy. Returns the object invisibly.


S4 Method for displaying figures.

Description

Method to display a summary of the figOutput object when printed.

Usage

## S4 method for signature 'figOutput'
show(object)

Arguments

object

An object of class "figOutput".

Value

Called for its side effect of displaying figures. Returns the object invisibly.


Standard methods for fitted nlpsem models

Description

Standard R methods for the myMxOutput objects returned by the nlpsem fitting functions. The existing S4 slots are unchanged, so saved objects from earlier versions can still be summarized and inspected.

Usage

## S4 method for signature 'myMxOutput'
show(object)

## S3 method for class 'myMxOutput'
print(x, digits = 4, ...)

## S3 method for class 'myMxOutput'
summary(object, ...)

## S3 method for class 'myMxOutput'
coef(object, ...)

## S3 method for class 'myMxOutput'
logLik(object, ...)

## S3 method for class 'myMxOutput'
plot(x, y, ..., xstarts = 0, xlab = "Time", outcome = NULL, draw = TRUE)

Arguments

x, object

A fitted myMxOutput object.

digits

Number of significant digits used by print().

...

Arguments forwarded to the underlying OpenMx summary() method. For plot() on a legacy object without saved specifications, named structural arguments accepted by getFigure(), such as sub_Model, y_var, curveFun, t_var, and records. Otherwise unused by the inspection methods. Structural plotting overrides are rejected for objects with a saved specification.

y

Unused. Supply plotting options by name.

xstarts

A numeric shift of the plotted time axis. Default is zero; the package does not infer time transformations made before fitting.

xlab

Label for the time axis. Default is "Time".

outcome

Display names for the longitudinal processes. By default, uses the saved outcome, mediator, and longitudinal predictor prefixes.

draw

Whether to display the generated figures. Set FALSE to obtain the figure object without drawing it.

Details

coef() returns the named, unrounded free parameters from the underlying OpenMx model, including parameters that are not shown in the derived Estimates table. logLik() delegates to OpenMx and retains its parameter-count and observation-count attributes for AIC() and BIC(). summary() delegates to OpenMx without refitting the model.

plot() uses getSpecification() to recover the fitted model's structural arguments and forwards them to getFigure(). Only display arguments (xstarts, xlab, outcome, and draw) may be overridden. Legacy fits require explicit plotting specifications; the method never attempts to reconstruct a missing specification from the model name. Original group labels remain available in getSpecification(); the concise print method reports the mapping to the fitted group codes.

Value

print() and show() return the fitted object invisibly. summary() returns the underlying OpenMx summary object. coef() returns a named numeric vector of free parameter estimates. logLik() returns an object of class logLik, with df (number of free parameters) and nobs (number of observations when available) attributes. plot() returns a figOutput object invisibly, drawing the figures first when draw = TRUE.

See Also

getSpecification, getFigure, ModelSummary, printTable

Examples

load(system.file("extdata", "getLGCM_examples.RData", package = "nlpsem"))
print(Math_LGCM_BLS_r)
head(coef(Math_LGCM_BLS_r))
logLik(Math_LGCM_BLS_r)
# The fit records its specification, so plotting takes only presentation choices:
figure <- plot(Math_LGCM_BLS_r, xlab = "Month", outcome = "Mathematics", draw = FALSE)