| Title: | Extended Hierarchical Structural Equation Models via h-Likelihood |
|---|---|
| Description: | An extended and re-engineered successor of the 'hsem' package (hierarchical structural equation models by h-likelihood), released under a new name because 'hsem' already exists on CRAN. It builds on the hierarchical-likelihood structural equation model of Caraka et al. (2021) <doi:10.3390/sym13040657> and Caraka et al. (2022) <doi:10.3390/su14010524>, and on h-likelihood work by Caraka et al. (2020) <doi:10.1109/ACCESS.2020.3033796> and Caraka et al. (2022) <doi:10.1186/s40537-022-00626-y>. Fits hierarchical (multilevel) structural equation models: systems of generalized linear mixed-effects regressions (Gaussian, binomial, Poisson, Gamma) in which random intercepts and random slopes of all equations are jointly distributed and may be correlated within and across equations (unstructured, block, diagonal, shared-factor and one-factor covariance structures), with optional regression models for the dispersion. Estimation uses the h-likelihood: exact maximum and restricted maximum likelihood for Gaussian models and Laplace approximations otherwise (Lee and Nelder (1996) <doi:10.1111/j.2517-6161.1996.tb02105.x>; Lee, Nelder and Pawitan (2006, ISBN:9781584886310)). Average direct, indirect and total effects account for random-slope covariances (Bauer, Preacher and Gil (2006) <doi:10.1037/1082-989X.11.2.142>). Neural-network components (multi-layer perceptron, residual, gated and deep-ensemble networks) can be added to the linear predictors. Includes path diagrams with random effects, assumption checks with simulation-based and randomized quantile residuals, lineup tests, cluster influence, parametric bootstrap, likelihood-ratio tests, cross-validation, Monte Carlo simulation studies with Monte Carlo standard errors and simulation-based power analysis. |
| Authors: | Rezzy Eko Caraka [aut, cre] |
| Maintainer: | Rezzy Eko Caraka <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 1.0.0 |
| Built: | 2026-12-02 00:40:53 UTC |
| Source: | https://github.com/cran/hsemx |
Likelihood-ratio tests between nested hsem models
## S3 method for class 'hsem' anova(object, ..., nsim = 0, seed = NULL, cores = 1L)## S3 method for class 'hsem' anova(object, ..., nsim = 0, seed = NULL, cores = 1L)
object, ...
|
Fitted |
nsim |
Number of parametric-bootstrap replicates for the null distribution (0 = asymptotic chi-square only). Recommended when the hypothesis puts a variance on the boundary (e.g. testing a random slope), where the chi-square p-value is conservative (Self & Liang, 1987). |
seed, cores
|
Passed to the bootstrap. |
A data frame of class anova.
Tidy parameter table
## S3 method for class 'hsem' as.data.frame(x, ...)## S3 method for class 'hsem' as.data.frame(x, ...)
x |
A fitted |
... |
Not used. |
A data frame with all fixed effects and variance parameters.
Confidence intervals
## S3 method for class 'hsem' confint( object, parm, level = 0.95, method = c("wald", "boot"), nsim = 200, ... )## S3 method for class 'hsem' confint( object, parm, level = 0.95, method = c("wald", "boot"), nsim = 200, ... )
object |
A fitted |
parm |
Ignored (all parameters are returned). |
level |
Confidence level. |
method |
|
nsim |
Bootstrap replicates when |
... |
Passed to |
Data frame of intervals.
Computes for by
Isserlis' theorem. For a two-link path this is the well-known
(Kenny, Korchmaros & Bolger, 2003).
expected_product(mu, S)expected_product(mu, S)
mu |
Mean vector. |
S |
Covariance matrix. |
A number.
expected_product(c(0.5, 0.4), matrix(c(0.1, 0.03, 0.03, 0.2), 2)) # 0.2 + 0.03expected_product(c(0.5, 0.4), matrix(c(0.1, 0.03, 0.03, 0.2), 2)) # 0.2 + 0.03
Fitted values
## S3 method for class 'hsem' fitted(object, type = c("response", "link"), ...)## S3 method for class 'hsem' fitted(object, type = c("response", "link"), ...)
object |
A fitted |
type |
|
... |
Not used. |
A named list with one vector per equation (a vector when the model has a single equation). Element names are data row names.
Extract fixed effects
## S3 method for class 'hsem' fixef(object, ...)## S3 method for class 'hsem' fixef(object, ...)
object |
A fitted |
... |
Not used. |
Named numeric vector; names are response~term.
hsem() fits a system of (generalized) linear mixed-effects regressions –
a multilevel path model – in one joint likelihood. Random effects of all
equations that share a grouping factor are collected into one vector whose
covariance matrix is estimated, so random intercepts and random slopes may be
correlated across equations (e.g. the covariance between the random
a-path and b-path in a multilevel mediation model).
hsem( equations, data, family = gaussian(), cov = "unstructured", dispformula = ~1, method = NULL, laplace = FALSE, hessian = TRUE, control = list(), start = NULL )hsem( equations, data, family = gaussian(), cov = "unstructured", dispformula = ~1, method = NULL, laplace = FALSE, hessian = TRUE, control = list(), start = NULL )
equations |
A formula or list of formulas in |
data |
A data frame. Each equation uses its own complete cases. |
family |
A family (or name) for all equations, or a list/character
vector with one per equation (optionally named by response). Supported:
|
cov |
Covariance structure of the random effects for each grouping
factor: |
dispformula |
One-sided formula (or list, one per equation) for the log
dispersion of Gaussian and Gamma equations, e.g. |
method |
|
laplace |
Logical; estimate fixed effects from the Laplace
approximation (only meaningful for non-Gaussian equations, |
hessian |
Compute standard errors of variance parameters. |
control |
List of control options: |
start |
Optional named list with |
An object of class "hsem".
For equation and observation in cluster :
Given the random effects, responses of different equations are conditionally independent, so endogenous variables may appear as predictors in later equations (a recursive path model). Cyclic (non-recursive) systems are rejected.
Parameters are estimated by the h-likelihood method. For fixed variance
parameters the joint mode of the h-likelihood in is found
by penalised IRLS (with , ).
Variance components and dispersion parameters maximise the adjusted profile
h-likelihood: for method = "ML" and for
method = "REML". For Gaussian responses with identity link these are the
exact ML and REML log-likelihoods. For non-Gaussian responses they are
first-order Laplace approximations; with laplace = TRUE the fixed effects
are also estimated from (the Laplace approximation to the
marginal likelihood, equivalent to lme4::glmer(nAGQ = 1)), otherwise they
come from the joint mode of (equivalent to glmer(nAGQ = 0)).
Standard errors of fixed effects come from the inverse of the Hessian of
(Henderson's mixed-model equations), and those of variance
parameters from the numerical Hessian of the outer objective with the
delta method. Wald tests are asymptotic (z); with few clusters use
hsem_boot().
Caraka, R. E., Noh, M., Chen, R. C., Lee, Y., Gio, P. U. and Pardamean, B. (2021). Connecting climate and communicable disease to penta helix using hierarchical likelihood structural equation modelling. Symmetry, 13(4), 657. doi:10.3390/sym13040657
Caraka, R. E., Noh, M., Lee, Y., et al. (2022). The impact of social media influencers Raffi Ahmad and Nagita Slavina on tourism visit intentions across millennials and zoomers using a hierarchical likelihood structural equation model. Sustainability, 14(1), 524. doi:10.3390/su14010524
Caraka, R. E., Noh, M. and Lee, Y. (2021). hsem: Hierarchical Structural Equation Model. R package version 1.0, CRAN.
Lee, Y. and Nelder, J. A. (1996). Hierarchical generalized linear models. JRSS B, 58, 619–678.
Lee, Y., Nelder, J. A. and Pawitan, Y. (2006). Generalized Linear Models with Random Effects: Unified Analysis via H-likelihood. Chapman & Hall.
Bauer, D. J., Preacher, K. J. and Gil, K. M. (2006). Conceptualizing and testing random indirect effects and moderated mediation in multilevel models. Psychological Methods, 11, 142–163.
data(mlmed) fit <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = mlmed) summary(fit) hsem_effects(fit, from = "x", to = "y", nsim = 2000) plot(fit, "twolevel")data(mlmed) fit <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = mlmed) summary(fit) hsem_effects(fit, from = "x", to = "y", nsim = 2000) plot(fit, "twolevel")
Simulates nsim data sets from the fitted model (new random effects,
propagated through the path model) and refits the model to each.
hsem_boot( fit, nsim = 200, FUN = NULL, seed = NULL, cores = 1L, propagate = TRUE ) ## S3 method for class 'hsem_boot' confint( object, parm = NULL, level = 0.95, type = c("percentile", "basic", "normal"), ... )hsem_boot( fit, nsim = 200, FUN = NULL, seed = NULL, cores = 1L, propagate = TRUE ) ## S3 method for class 'hsem_boot' confint( object, parm = NULL, level = 0.95, type = c("percentile", "basic", "normal"), ... )
fit |
A fitted |
nsim |
Number of bootstrap replicates. |
FUN |
Optional function of a fitted model returning a named numeric vector of extra statistics (e.g. an indirect effect). |
seed |
Optional seed (data are generated sequentially, so results are
reproducible also when |
cores |
Number of cores (forked; ignored on Windows). |
propagate |
Passed to |
object |
An |
parm |
Optional parameter names. |
level |
Confidence level. |
type |
|
... |
Not used. |
An object of class hsem_boot.
data(mlmed) fit <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = mlmed) ind <- function(f) c(indirect = hsem_effects(f, "x", "y", ci = "delta")$ table$estimate[1]) bt <- hsem_boot(fit, nsim = 50, FUN = ind, seed = 1) confint(bt)data(mlmed) fit <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = mlmed) ind <- function(f) c(indirect = hsem_effects(f, "x", "y", ci = "delta")$ table$estimate[1]) bt <- hsem_boot(fit, nsim = 50, FUN = ind, seed = 1) confint(bt)
Adds <var>_cm (cluster mean) and <var>_cw (deviation from the cluster
mean) for each variable. Using _cw as a level-1 predictor and _cm as a
level-2 predictor separates within- from between-cluster effects
(Enders & Tofighi, 2007; Zhang, Zyphur & Preacher, 2009).
hsem_center(data, vars, cluster, grand = TRUE)hsem_center(data, vars, cluster, grand = TRUE)
data |
A data frame. |
vars |
Character vector of numeric variables. |
cluster |
Name of the cluster variable. |
grand |
If |
data with added columns.
d <- hsem_center(mlmed, c("x", "m"), "cluster") head(d)d <- hsem_center(mlmed, c("x", "m"), "cluster") head(d)
Computes, for every equation, conditional residuals (Pearson and randomized quantile), simulation-based scaled residuals (probability-integral transform of the observed response within responses simulated from the fitted model, as in the DHARMa approach), standardized predicted random effects, collinearity diagnostics, and a battery of formal tests:
hsem_check( fit, nsim = 250, time = NULL, seed = NULL, influence = FALSE, cores = 1L )hsem_check( fit, nsim = 250, time = NULL, seed = NULL, influence = FALSE, cores = 1L )
fit |
A fitted |
nsim |
Number of simulated data sets for scaled residuals. |
time |
Optional name of a time variable (for serial correlation). |
seed |
Optional seed. |
influence |
Also compute cluster-deletion influence ( |
cores |
Cores for the influence refits. |
Shapiro-Wilk test of the quantile residuals (exactly N(0,1) under the model, also for discrete responses), and a Kolmogorov-Smirnov test of uniformity of the scaled residuals.
Simulation test comparing the observed sum of squared response residuals with its simulated distribution (two-sided).
Binomial test of the number of observations outside the simulation envelope.
(Counts and binary data) simulated distribution of the number of zeros.
Koenker's studentized Breusch-Pagan test against the fitted values and a Brown-Forsythe test across clusters.
F-test of a cubic polynomial of each numeric predictor on the quantile residuals.
Shapiro-Wilk test of the predicted random effects
standardized by their marginal SD .
(If time is given) pooled within-cluster
lag-1 autocorrelation of the quantile residuals (Fisher z-test).
Variance inflation factors (flag > 5).
Residuals and simulations are conditional on the predicted random effects,
so level-1 and level-2 assumptions are checked separately. With large
samples tiny departures become "significant": read the tests together with
the plots (plot.hsem_check()).
An object of class hsem_check.
Dunn, P. K. and Smyth, G. K. (1996). Randomized quantile residuals. J. Comput. Graph. Stat., 5, 236–244.
Hartig, F. (2022). DHARMa: residual diagnostics for hierarchical regression models. R package.
Koenker, R. (1981). A note on studentizing a test for heteroscedasticity. J. Econometrics, 17, 107–112.
Cluster-level (or row-level) K-fold cross-validation of the linear
hsem() model and of hsem_nn() with several architectures. For held-out
clusters predictions are marginal (random effects = 0); for held-out rows
they use the predicted random effects of the training fit.
hsem_cv( equations, data, nn, cluster, family = gaussian(), architectures = c("linear", "mlp", "resnet", "glu", "ensemble"), folds = 5, split = c("cluster", "row"), equation = NULL, seed = NULL, ... )hsem_cv( equations, data, nn, cluster, family = gaussian(), architectures = c("linear", "mlp", "resnet", "glu", "ensemble"), folds = 5, split = c("cluster", "row"), equation = NULL, seed = NULL, ... )
equations, data, family, nn
|
As in |
cluster |
Name of the clustering variable (for |
architectures |
Character vector; |
folds |
Number of folds. |
split |
|
equation |
Response whose predictive performance is reported. |
seed |
Optional seed. |
... |
Further arguments to |
An object of class hsem_cv with per-fold and summary metrics
(RMSE, MAE and mean negative log predictive density for Gaussian
outcomes, Brier score / log-loss for binomial, deviance for Poisson).
Enumerates every directed path from from to to and computes the
average (population) effect of each path. With random slopes the
average effect of a path is the expectation of the product of the
cluster-specific coefficients, e.g.
for a two-link path, and in general the Isserlis expansion (see
expected_product()). Random effects of different grouping factors are
independent, so their covariances are zero.
hsem_effects( fit, from, to, level = 0.95, ci = c("montecarlo", "delta"), nsim = 10000, seed = NULL )hsem_effects( fit, from, to, level = 0.95, ci = c("montecarlo", "delta"), nsim = 10000, seed = NULL )
fit |
A fitted |
from, to
|
Variable names (cause and outcome). |
level |
Confidence level. |
ci |
|
nsim |
Monte Carlo draws. |
seed |
Optional seed. |
Effects are on the scale of the linear predictors. For equations
with a non-identity link the product of coefficients is not a causal
indirect effect on the response scale; a warning is issued. As usual for
level-1 mediation, centre the mediator within clusters
(hsem_center()) so that within- and between-cluster effects are not
conflated (Zhang, Zyphur & Preacher, 2009).
An object of class hsem_effects with a table of effects, the
decomposition of each indirect path into the product of fixed
coefficients and the random-slope covariance contribution, the share of
clusters with a positive effect, and cluster-specific effects.
Kenny, D. A., Korchmaros, J. D. and Bolger, N. (2003). Lower level mediation in multilevel models. Psychological Methods, 8, 115–128.
Preacher, K. J. and Selig, J. P. (2012). Advantages of Monte Carlo confidence intervals for indirect effects. Communication Methods and Measures, 6, 77–98.
Refits the model leaving out one cluster at a time and reports Cook's
distance and the largest scaled change in any fixed
effect (DFBETAS).
hsem_influence(fit, group = NULL, cores = 1L)hsem_influence(fit, group = NULL, cores = 1L)
fit |
A fitted |
group |
Grouping variable (a column of the data; default: the first grouping factor). |
cores |
Number of forked cores. |
An object of class hsem_influence.
Creates <var>_lag<k> (value at time for the same cluster), with
NA when the previous occasion is not observed. Gaps in time are
respected: a value is only lagged from occasion time - k.
hsem_lag(data, vars, cluster, time, k = 1L)hsem_lag(data, vars, cluster, time, k = 1L)
data |
A data frame. |
vars |
Variables to lag. |
cluster |
Cluster identifier. |
time |
Integer time index. |
k |
Lag order. |
data with added columns.
d <- hsem_lag(ml2[, c("urge", "dep", "id", "time")], c("urge", "dep"), "id", "time") head(d)d <- hsem_lag(ml2[, c("urge", "dep", "id", "time")], c("urge", "dep"), "id", "time") head(d)
Implements the lineup protocol of Buja et al. (2009): the diagnostic plot of
the observed data is hidden at a random position among n - 1 plots made
from data simulated from the fitted model and refitted. If an observer who
has not seen the real plot can pick it out, the model is rejected at level
(for one observer). Reveal the position with lineup_answer().
hsem_lineup( fit, equation = 1, type = c("resid", "qq", "ranef"), n = 20, refit = TRUE, seed = NULL, cores = 1L )hsem_lineup( fit, equation = 1, type = c("resid", "qq", "ranef"), n = 20, refit = TRUE, seed = NULL, cores = 1L )
fit |
A fitted |
equation |
Equation (name or index). |
type |
|
n |
Number of panels. |
refit |
Refit the model to each null data set (recommended; residuals of a fitted model are not the same as errors). |
seed |
Optional seed. |
cores |
Cores for refits. |
A ggplot object with the answer stored (obfuscated) as an attribute.
Buja, A., Cook, D., Hofmann, H., Lawrence, M., Lee, E.-K., Swayne, D. F. and Wickham, H. (2009). Statistical inference for exploratory data analysis and model diagnostics. Phil. Trans. R. Soc. A, 367, 4361–4383.
Adds a flexible neural-network component of selected
covariates to the linear predictor of one or more equations of an hsem()
model, while keeping the interpretable linear paths, the cross-equation
random effects and the h-likelihood estimation of the variance components.
hsem_nn( equations, data, nn, family = gaussian(), cov = "unstructured", dispformula = ~1, method = NULL, architecture = c("mlp", "resnet", "glu", "ensemble"), hidden = c(32, 16), activation = "relu", dropout = 0, weight_decay = 1e-04, lr = 0.003, epochs = 100, batch_size = 64, patience = 15, validation = 0.2, n_ensemble = 5, rounds = 8, tol = 1e-04, seed = NULL, verbose = FALSE )hsem_nn( equations, data, nn, family = gaussian(), cov = "unstructured", dispformula = ~1, method = NULL, architecture = c("mlp", "resnet", "glu", "ensemble"), hidden = c(32, 16), activation = "relu", dropout = 0, weight_decay = 1e-04, lr = 0.003, epochs = 100, batch_size = 64, patience = 15, validation = 0.2, n_ensemble = 5, rounds = 8, tol = 1e-04, seed = NULL, verbose = FALSE )
equations, data, family, cov, dispformula, method
|
As in |
nn |
A one-sided formula of network inputs for a single-equation model,
or a named list of one-sided formulas (names = responses), e.g.
|
architecture |
|
, activation, dropout
|
Network settings (see |
weight_decay |
L2 penalty on network weights. |
lr, epochs, batch_size, patience
|
Adam optimiser settings. |
validation |
Fraction of rows used for early stopping. |
n_ensemble |
Members for |
rounds |
Maximum alternation rounds. |
tol |
Convergence tolerance on the relative change of the adjusted profile log-likelihood between rounds. The Adam learning rate is annealed by a factor 0.6 per round so that the stochastic network updates settle. |
seed |
Optional seed. |
verbose |
Print progress. |
Standard errors of and variance components are
conditional on the estimated network function.
An object of class hsem_nn (with element fit, the final
hsem() fit using the network output as an offset).
Caraka, R. E., Lee, Y., Chen, R. C. and Toharudin, T. (2020). Using hierarchical likelihood towards support vector machine: theory and its application. IEEE Access, 8, 194795–194807. doi:10.1109/ACCESS.2020.3033796
Lee, H. and Lee, Y. (2023). H-likelihood approach to deep neural networks with temporal-spatial random effects for high-cardinality categorical features. Proc. 40th ICML, PMLR 202.
Simchoni, G. and Rosset, S. (2021). Using random effects to account for high-cardinality categorical features and repeated measures in deep neural networks. NeurIPS, 34.
d <- hsem_sim_mediation(J = 40, nj = 15, nonlinear = TRUE, seed = 2) nnfit <- hsem_nn(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = d, nn = list(y = ~ z1 + z2), architecture = "resnet", hidden = c(32, 32, 32), seed = 1) nnfitd <- hsem_sim_mediation(J = 40, nj = 15, nonlinear = TRUE, seed = 2) nnfit <- hsem_nn(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = d, nn = list(y = ~ z1 + z2), architecture = "resnet", hidden = c(32, 32, 32), seed = 1) nnfit
For each network input, plots – the network output
averaged over the observed values of the other inputs – across a grid of
the input (Friedman, 2001), with the individual ensemble members when
architecture = "ensemble".
hsem_nn_pdp( x, equation = names(x$nn)[1], vars = NULL, grid = 40, base_size = 11 )hsem_nn_pdp( x, equation = names(x$nn)[1], vars = NULL, grid = 40, base_size = 11 )
x |
An |
equation |
Response whose network is shown. |
vars |
Inputs to show (default: all numeric inputs). |
grid |
Grid size. |
base_size |
Base font size. |
A ggplot object.
Named colours used by all hsem graphics. Categorical slots are used in
fixed order (blue, orange, aqua, ...); signed quantities use the
diverging pair (neg red, mid neutral grey, pos blue).
hsem_palette()hsem_palette()
A named character vector of hex colours.
hsem_palette()hsem_palette()
For every random coefficient, shows the cluster-specific value
with a 95% prediction interval
( times the square root of the prediction error variance),
sorted, against the population average (line) and the 95% range of the
estimated population distribution
(band).
hsem_plot_forest(fit, group = NULL, coefs = NULL, base_size = 11)hsem_plot_forest(fit, group = NULL, coefs = NULL, base_size = 11)
fit |
A fitted |
group |
Grouping factor (default: the first). |
coefs |
Optional subset of random coefficient names ( |
base_size |
Base font size. |
A ggplot object.
Draws the path model with its random effects in one of three visual grammars (see Details).
hsem_plot_path( fit, style = c("classic", "twolevel", "clusters"), show_cor = c("significant", "all", "none"), clusters = NULL, digits = 2, title = NULL, subtitle = NULL, base_size = 11 )hsem_plot_path( fit, style = c("classic", "twolevel", "clusters"), show_cor = c("significant", "all", "none"), clusters = NULL, digits = 2, title = NULL, subtitle = NULL, base_size = 11 )
fit |
A fitted |
style |
|
show_cor |
Which random-effect correlations to draw: |
clusters |
For |
digits |
Decimals for coefficients. |
title, subtitle
|
Plot titles ( |
base_size |
Base font size. |
classic – arrows carry fixed path coefficients (solid = p < .05,
dashed = n.s.; blue positive, red negative). A filled dot on an arrow
marks a random slope, annotated with its SD across clusters
(Bauer, Preacher & Gil, 2006). A circle above an endogenous variable marks
its random intercept. Dashed violet curves connect random effects that
are correlated (with ).
twolevel – the multilevel-SEM depiction (Preacher, Zyphur & Zhang, 2010): the lower band is the within-cluster path model, the upper band shows each random coefficient as a latent between-cluster variable (circle, with its SD) pointing at the intercept or slope it modifies, and the correlations among them.
clusters – the path model re-drawn for selected clusters with the
cluster-specific coefficients (colour and width
encode sign and size).
A ggplot object.
fit <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = mlmed) hsem_plot_path(fit) hsem_plot_path(fit, style = "twolevel") hsem_plot_path(fit, style = "clusters")fit <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = mlmed) hsem_plot_path(fit) hsem_plot_path(fit, style = "twolevel") hsem_plot_path(fit, style = "clusters")
Lower-triangular heat map of the estimated correlation matrix of all random effects of a grouping factor, within and across equations; cells whose 95% CI excludes zero are marked with a dot.
hsem_plot_recor(fit, group = NULL, base_size = 11)hsem_plot_recor(fit, group = NULL, base_size = 11)
fit |
A fitted |
group |
Grouping factor (default: the first). |
base_size |
Base font size. |
A ggplot object.
Draws, for each random coefficient, the estimated population distribution
of cluster-specific values, the
predicted values of the observed clusters (dots), and the estimated share
of clusters with a positive coefficient .
hsem_plot_ridge(fit, group = NULL, coefs = NULL, base_size = 11)hsem_plot_ridge(fit, group = NULL, coefs = NULL, base_size = 11)
fit |
A fitted |
group |
Grouping factor (default: the first). |
coefs |
Optional subset of random coefficient names ( |
base_size |
Base font size. |
A ggplot object.
Simulation-based power analysis over numbers of clusters
hsem_power( J, nrep, generate, fit, parameter, truth, extract = .default_extract, alpha = 0.05, seed = NULL, cores = 1L )hsem_power( J, nrep, generate, fit, parameter, truth, extract = .default_extract, alpha = 0.05, seed = NULL, cores = 1L )
J |
Vector of numbers of clusters. |
nrep |
Replications per design point. |
generate |
Function |
fit |
Function |
parameter |
Parameter name(s) whose rejection rate is the power. |
truth |
Named true values (used for bias/coverage). |
extract, alpha, seed, cores
|
See |
An object of class hsem_power.
Variance decomposition of Nakagawa & Schielzeth (2013), with random slopes
handled as in Johnson (2014) and distribution-specific residual variances of
Nakagawa, Johnson & Schielzeth (2017): logit , probit 1,
cloglog , Poisson-log (log-normal
approximation), Gamma-log (trigamma).
hsem_r2(fit)hsem_r2(fit)
fit |
A fitted |
Data frame with fixed, random and residual variances, marginal and
conditional , and the adjusted ICC.
Nakagawa, S., Johnson, P. C. D. and Schielzeth, H. (2017). The coefficient of determination R2 and intra-class correlation coefficient from generalized linear mixed-effects models revisited and expanded. J. R. Soc. Interface, 14, 20170213.
Refit an hsem model to new data
hsem_refit(fit, data, hessian = FALSE, warm = TRUE, ...)hsem_refit(fit, data, hessian = FALSE, warm = TRUE, ...)
fit |
A fitted |
data |
New data frame (same variables). |
hessian |
Compute variance-parameter standard errors. |
warm |
Use the current estimates as starting values. |
... |
Further arguments overriding those of the original call. |
A fitted hsem object.
Generates data in which the intercepts
and all three paths may vary across clusters and the random a- and b-paths
may covary. Optionally adds a nonlinear effect of two covariates on y
(useful for comparing hsem() with hsem_nn()).
hsem_sim_mediation( J = 50, nj = 20, a = 0.5, b = 0.4, cp = 0.2, int_m = 0, int_y = 0, sd = c(int_m = 0.5, a = 0.3, int_y = 0.5, b = 0.3, cp = 0), cor = 0.4, sigma_m = 1, sigma_y = 1, family_y = c("gaussian", "binomial", "poisson"), nonlinear = FALSE, seed = NULL )hsem_sim_mediation( J = 50, nj = 20, a = 0.5, b = 0.4, cp = 0.2, int_m = 0, int_y = 0, sd = c(int_m = 0.5, a = 0.3, int_y = 0.5, b = 0.3, cp = 0), cor = 0.4, sigma_m = 1, sigma_y = 1, family_y = c("gaussian", "binomial", "poisson"), nonlinear = FALSE, seed = NULL )
J |
Number of clusters. |
nj |
Cluster size: a number, or a length-2 vector |
a, b, cp
|
Average paths. |
int_m, int_y
|
Average intercepts. |
sd |
Named SDs of the random effects: |
cor |
5 x 5 correlation matrix of the random effects (order as |
sigma_m, sigma_y
|
Level-1 residual SDs ( |
family_y |
|
nonlinear |
Add |
seed |
Optional seed. |
Model: ,
with . The population average indirect effect is
.
A data frame with attribute "truth" (true parameters, including
the average indirect effect).
d <- hsem_sim_mediation(J = 30, nj = 10, seed = 1) attr(d, "truth")$indirectd <- hsem_sim_mediation(J = 30, nj = 10, seed = 1) attr(d, "truth")$indirect
Person-specific means, autoregressive and cross-lagged coefficients:
. This is the
data-generating model behind the ml2 example (urge to smoke and
depression). Clusters whose is not stationary are redrawn.
hsem_sim_var1( J = 50, T = 30, mu = c(0, 0), Phi = matrix(c(0.4, 0.1, 0.15, 0.3), 2), sd_mu = c(0.5, 0.5), sd_phi = matrix(0.1, 2, 2), sigma = c(1, 1), rho_e = 0.3, burnin = 50, names = c("y1", "y2"), seed = NULL )hsem_sim_var1( J = 50, T = 30, mu = c(0, 0), Phi = matrix(c(0.4, 0.1, 0.15, 0.3), 2), sd_mu = c(0.5, 0.5), sd_phi = matrix(0.1, 2, 2), sigma = c(1, 1), rho_e = 0.3, burnin = 50, names = c("y1", "y2"), seed = NULL )
J |
Number of persons. |
T |
Number of occasions retained. |
mu |
Average means (length 2). |
Phi |
Average 2 x 2 lag matrix (row = outcome, column = lagged predictor). |
sd_mu |
SDs of person means. |
sd_phi |
2 x 2 matrix of SDs of the person-specific lag coefficients. |
sigma |
Innovation SDs (length 2). |
rho_e |
Innovation correlation. |
burnin |
Burn-in occasions. |
names |
Names of the two series. |
seed |
Optional seed. |
Long data frame with id, time, the two series and their within-
person lags (<name>_lag1).
Runs nrep replications of generate -> fit -> extract and reports, for
every parameter in truth, the performance measures of Morris, White &
Crowther (2019) together with their Monte Carlo standard errors (MCSE):
bias, relative bias, empirical SE, average model SE, relative error of the
model SE, RMSE, coverage, bias-eliminated coverage and rejection rate
(power / type-I error).
hsem_simstudy( nrep, generate, fit, truth, extract = .default_extract, alpha = 0.05, seed = NULL, cores = 1L, progress = FALSE )hsem_simstudy( nrep, generate, fit, truth, extract = .default_extract, alpha = 0.05, seed = NULL, cores = 1L, progress = FALSE )
nrep |
Number of replications. |
generate |
Function |
fit |
Function |
truth |
Named numeric vector of true values (names as returned by
|
extract |
Function |
alpha |
Significance level for the rejection rate. |
seed |
Optional seed; replication |
cores |
Number of forked cores. |
progress |
Print progress. |
An object of class hsem_simstudy.
Morris, T. P., White, I. R. and Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38, 2074–2102.
ss <- hsem_simstudy( nrep = 20, generate = function(r) hsem_sim_mediation(J = 30, nj = 10), fit = function(d) hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), d), truth = c("m~x" = 0.5, "y~m" = 0.4, "y~x" = 0.2), seed = 1) ss plot(ss)ss <- hsem_simstudy( nrep = 20, generate = function(r) hsem_sim_mediation(J = 30, nj = 10), fit = function(d) hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), d), truth = c("m~x" = 0.5, "y~m" = 0.4, "y~x" = 0.2), seed = 1) ss plot(ss)
Translates an hsem 1.0 call into hsem(). structure = "correlated" maps
to cov = "unstructured", "independent" to "diagonal" and "shared"
to "shared"; mord = 1 maps to laplace = TRUE.
hsemfit( RespDist = "gaussian", BinomialDen = NULL, DataMain, MeanModel, DispersionModel = NULL, PhiFix = NULL, LamFix = NULL, structure = "correlated", mord = 0, dord = 1, convergence = 1e-05, Init_Corr = NULL, EstimateCorrelations = TRUE )hsemfit( RespDist = "gaussian", BinomialDen = NULL, DataMain, MeanModel, DispersionModel = NULL, PhiFix = NULL, LamFix = NULL, structure = "correlated", mord = 0, dord = 1, convergence = 1e-05, Init_Corr = NULL, EstimateCorrelations = TRUE )
RespDist |
Response distributions (one per model). |
BinomialDen |
Optional binomial denominators (list or vector). |
DataMain |
A data frame or a list of identical data frames. |
MeanModel |
List of |
DispersionModel |
List of |
PhiFix, LamFix
|
Not supported (must be |
structure |
|
mord |
Order of the Laplace approximation for the mean parameters. |
dord |
Ignored (dispersion parameters always use the first-order adjusted profile likelihood). |
convergence |
Ignored (the optimiser has its own tolerances). |
Init_Corr |
Ignored. |
EstimateCorrelations |
If |
A fitted hsem object.
Kept so that scripts written for hsem 1.0 still run. New code should use
hsem() directly.
hsemmodeling( Model = "mean", Link = NULL, LinPred = "constant", RandDist = NULL, Offset = NULL, LMatrix = NULL, LinkRandVariance = NULL, LinPredRandVariance = NULL, RandDistRandVariance = "gaussian", LinkRandVariance2 = NULL, LinPredRandVariance2 = NULL )hsemmodeling( Model = "mean", Link = NULL, LinPred = "constant", RandDist = NULL, Offset = NULL, LMatrix = NULL, LinkRandVariance = NULL, LinPredRandVariance = NULL, RandDistRandVariance = "gaussian", LinkRandVariance2 = NULL, LinPredRandVariance2 = NULL )
Model |
|
Link |
Link function name. |
LinPred |
Formula. As in hsem 1.0, each random term |
RandDist |
Distribution(s) of the random effects; only |
Offset, LMatrix, LinkRandVariance, LinPredRandVariance, RandDistRandVariance, LinkRandVariance2, LinPredRandVariance2
|
hsem 1.0 options; only their defaults ( |
An object of class hsemmodeling.
Reveal the position of the observed data in a lineup
lineup_answer(lineup)lineup_answer(lineup)
lineup |
A plot returned by |
The panel number (integer).
A simulated subset following the urge-to-smoke example of McNeish and Hamaker (2020): 20 persons with 10 equally spaced occasions each.
ml2ml2
A data frame with 200 rows and 6 variables:
standardized urge to smoke
urge at the previous occasion (lag 1)
standardized depression
depression at the previous occasion (lag 1)
person identifier
occasion (1–10)
At time == 1 the lagged variables are coded 0 although the
previous occasion is not observed. Exclude the first occasion
(subset(ml2, time > 1)) or rebuild the lags with hsem_lag(), which
returns NA there.
Simulated; originally distributed with the CRAN package hsem 1.0.
McNeish, D. and Hamaker, E. L. (2020). A primer on two-level dynamic structural equation models for intensive longitudinal data in Mplus. Psychological Methods, 25, 610–635.
Generated by hsem_sim_mediation() (see data-raw/make_data.R) with 50
clusters of 20 observations: , , ,
random-effect SDs 0.5 (intercept of m), 0.35 (a-path), 0.5 (intercept of
y), 0.3 (b-path), 0.1 (c'-path), correlation 0.5 between the random a- and
b-paths, so the average indirect effect is . z1, z2 enter y nonlinearly through
(column g_true).
mlmedmlmed
A data frame with 1000 rows: cluster, x, m, y, z1, z2,
g_true.
Simulated.
Network component values
nn_component( object, newdata = NULL, equation = names(object$nn)[1], members = FALSE )nn_component( object, newdata = NULL, equation = names(object$nn)[1], members = FALSE )
object |
An |
newdata |
Data frame (defaults to the training data). |
equation |
Response name. |
members |
Return the matrix of ensemble members instead of the mean. |
Numeric vector (or matrix) of centred network outputs .
Convenience dispatcher to the hsem graphics.
## S3 method for class 'hsem' plot( x, type = c("path", "twolevel", "clusters", "forest", "ridge", "recor", "diagnostics"), ... )## S3 method for class 'hsem' plot( x, type = c("path", "twolevel", "clusters", "forest", "ridge", "recor", "diagnostics"), ... )
x |
A fitted |
type |
One of |
... |
Passed to the underlying function ( |
A ggplot / patchwork object.
fit <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = mlmed) plot(fit) plot(fit, "ridge")fit <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)), data = mlmed) plot(fit) plot(fit, "ridge")
Diagnostic dashboard
## S3 method for class 'hsem_check' plot(x, equation = 1, which = "all", base_size = 11, ...)## S3 method for class 'hsem_check' plot(x, equation = 1, which = "all", base_size = 11, ...)
x |
An |
equation |
Equation (name or index). |
which |
Panels to show: any of |
base_size |
Base font size. |
... |
Not used. |
A patchwork object.
Three panels: (1) every path effect with its confidence interval, with the indirect effects split into the product of fixed coefficients and the random-slope covariance contribution; (2) the Monte Carlo sampling distribution of the total indirect effect; (3) cluster-specific indirect effects.
## S3 method for class 'hsem_effects' plot(x, base_size = 11, ...)## S3 method for class 'hsem_effects' plot(x, base_size = 11, ...)
x |
An |
base_size |
Base font size. |
... |
Not used. |
A patchwork/ggplot object.
type = "performance" shows bias, coverage, relative error of the model SE
and rejection rate with Monte Carlo 95% intervals; type = "zip" draws the
zip plot of Morris et al. (2019) of the confidence intervals of one
parameter, ranked by their fractional centile of .
## S3 method for class 'hsem_simstudy' plot(x, type = c("performance", "zip"), parameter = NULL, base_size = 11, ...)## S3 method for class 'hsem_simstudy' plot(x, type = c("performance", "zip"), parameter = NULL, base_size = 11, ...)
x |
An |
type |
|
parameter |
Parameter for the zip plot (default: the first). |
base_size |
Base font size. |
... |
Not used. |
A ggplot / patchwork object.
Predictions from an hsem fit
## S3 method for class 'hsem' predict( object, newdata = NULL, type = c("response", "link"), re = c("conditional", "marginal"), ... )## S3 method for class 'hsem' predict( object, newdata = NULL, type = c("response", "link"), re = c("conditional", "marginal"), ... )
object |
A fitted |
newdata |
Optional data frame. Unknown cluster levels get random effects equal to zero (the population-average conditional prediction). |
type |
|
re |
|
... |
Not used. |
Named list per equation (a vector for single-equation models).
Predictions from an NN-augmented hsem
## S3 method for class 'hsem_nn' predict( object, newdata = NULL, type = c("response", "link"), re = c("conditional", "marginal"), ... )## S3 method for class 'hsem_nn' predict( object, newdata = NULL, type = c("response", "link"), re = c("conditional", "marginal"), ... )
object |
An |
newdata |
Data frame. |
type |
|
re |
|
... |
Not used. |
Named list per equation (vector for single-equation models).
Conditional modes (BLUPs) of the random effects
## S3 method for class 'hsem' ranef(object, condVar = FALSE, ...)## S3 method for class 'hsem' ranef(object, condVar = FALSE, ...)
object |
A fitted |
condVar |
Attach the prediction-error covariance array ( |
... |
Not used. |
A named list (one matrix per grouping factor; rows = levels).
Residuals of an hsem fit
## S3 method for class 'hsem' residuals(object, type = c("response", "pearson", "deviance", "quantile"), ...)## S3 method for class 'hsem' residuals(object, type = c("response", "pearson", "deviance", "quantile"), ...)
object |
A fitted |
type |
|
... |
Not used. |
Named list per equation (vector for a single equation). All types are conditional on the predicted random effects.
Dunn, P. K. and Smyth, G. K. (1996). Randomized quantile residuals. J. Comput. Graph. Stat., 5, 236–244.
Simulate responses from a fitted hsem
## S3 method for class 'hsem' simulate( object, nsim = 1, seed = NULL, re = c("new", "conditional"), propagate = TRUE, ... )## S3 method for class 'hsem' simulate( object, nsim = 1, seed = NULL, re = c("new", "conditional"), propagate = TRUE, ... )
object |
A fitted |
nsim |
Number of simulated data sets. |
seed |
Optional seed. |
re |
|
propagate |
If |
... |
Not used. |
A list of nsim data frames.
Bivariate multilevel VAR(1) generated by hsem_sim_var1() (see
data-raw/make_data.R): 80 persons, 40 occasions, average lag matrix
(rows: outcome urge, dep;
columns: lagged urge, dep), person-specific means (SD 0.6, 0.5) and
person-specific lag coefficients (SD 0.1), innovation SDs 1 and 0.8 with
correlation 0.3.
smoke_emasmoke_ema
A data frame with 3200 rows: id, time, urge, dep,
urge_lag1, dep_lag1 (lags are NA at the first occasion).
Simulated.
Summarise an hsem fit
## S3 method for class 'hsem' summary(object, level = 0.95, ...)## S3 method for class 'hsem' summary(object, level = 0.95, ...)
object |
A fitted |
level |
Confidence level for intervals. |
... |
Not used. |
An object of class summary.hsem.
ggplot2 theme for hsem graphics
theme_hsem(base_size = 11, base_family = "", grid = "xy")theme_hsem(base_size = 11, base_family = "", grid = "xy")
base_size |
Base font size. |
base_family |
Font family. |
grid |
|
A ggplot2 theme.
Random-effect covariance matrices
## S3 method for class 'hsem' VarCorr(x, sigma = 1, ...)## S3 method for class 'hsem' VarCorr(x, sigma = 1, ...)
x |
A fitted |
sigma |
Ignored (for compatibility with the generic). |
... |
Not used. |
A named list of covariance matrices (one per grouping factor).