| Type: | Package |
| Title: | Extended Hierarchical Structural Equation Models via h-Likelihood |
| Version: | 1.0.0 |
| Date: | 2026-11-09 |
| Maintainer: | Rezzy Eko Caraka <rezzyekocaraka@gmail.com> |
| 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. |
| License: | GPL (≥ 3) |
| Encoding: | UTF-8 |
| Depends: | R (≥ 4.1.0) |
| Imports: | Matrix (≥ 1.6-0), numDeriv, nlme, ggplot2 (≥ 3.4.0), patchwork, grid, methods, stats, utils, parallel |
| Suggests: | lme4, glmmTMB, testthat (≥ 3.0.0), knitr, rmarkdown |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| LazyData: | true |
| RoxygenNote: | 7.3.1 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-09 04:03:34 UTC; root |
| Author: | Rezzy Eko Caraka [aut, cre] |
| Repository: | CRAN |
| Date/Publication: | 2026-12-01 15:00:02 UTC |
hsemx: 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 (multilayer, 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.
About
hsemx (hsem extended) is an extended and re-engineered successor of the
CRAN package hsem 1.0 (Caraka, Noh and Lee, 2021), which introduced
hierarchical structural equation models fitted by h-likelihood. It builds
on the h-likelihood research programme of Caraka and co-authors: the
hierarchical-likelihood structural equation model (HSEM) and its
applications (Caraka et al., 2021, Symmetry; Caraka et al., 2022,
Sustainability), h-likelihood for machine learning (Caraka et al., 2020,
IEEE Access), and h-likelihood software (Caraka et al., 2022,
Journal of Big Data) – see References. It is
published under a new name because hsem already exists on CRAN; the two
packages can be installed side by side (attach only one per session, as
both export hsem()).
What is extended relative to hsem 1.0:
a new estimation engine: exact ML/REML for Gaussian models and Laplace approximations with observed information otherwise, validated against lme4, nlme and glmmTMB;
random-effect covariances estimated within and across equations (unstructured, block, diagonal, shared-factor, one-factor);
any number of equations and of nested or crossed grouping factors, lme4 formula syntax, dispersion regression models;
average direct / indirect / total effects with random slopes;
neural-network components (MLP, residual, gated, deep ensemble);
path diagrams with random effects, assumption diagnostics, lineup tests, influence, bootstrap, likelihood-ratio tests, simulation studies and power.
Scripts written for hsem 1.0 can use the compatibility wrappers
hsemfit() and hsemmodeling(). Random effects in dispersion models and
non-normal random effects of hsem 1.0 are not carried over.
Model
Multilevel (hierarchical) path models for Gaussian and non-Gaussian responses with random intercepts and random slopes that are correlated within and across equations, estimated by the h-likelihood.
Main functions:
-
hsem()– fit a hierarchical SEM;hsem_nn()– the same with neural-network components (MLP, residual, gated, deep-ensemble networks). -
hsem_effects()– direct, indirect and total effects with random slopes. -
hsem_plot_path(),hsem_plot_forest(),hsem_plot_ridge(),hsem_plot_recor()– path diagrams with random effects and random-effect graphics. -
hsem_check(),hsem_lineup(),hsem_influence()– assumption checks, visual inference and influence. -
hsem_boot(),anova.hsem(),hsem_simstudy(),hsem_power(),hsem_cv()– bootstrap, likelihood-ratio tests, Monte Carlo studies, power analysis and cross-validation.
Author(s)
Maintainer: Rezzy Eko Caraka rezzyekocaraka@gmail.com
References
Caraka, R. E., Noh, M. and Lee, Y. (2021). hsem: Hierarchical Structural Equation Model. R package version 1.0, CRAN.
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
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., Toharudin, T., Yusra, Tyasti, A. E., Royanow, A. F., Dewata, D. P., Gio, P. U., Basyuni, M. and Pardamean, B. (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., Lee, Y., Han, J., Lee, H., Noh, M., Ha, I. D., Gio, P. U. et al. (2022). Albatross analytics a hands-on into practice: statistical and data science application. Journal of Big Data, 9, 70. doi:10.1186/s40537-022-00626-y
Lee, Y. and Nelder, J. A. (1996). Hierarchical generalized linear models (with discussion). Journal of the Royal Statistical Society 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/CRC.
Random-effect covariance matrices
Description
Random-effect covariance matrices
Usage
## S3 method for class 'hsem'
VarCorr(x, sigma = 1, ...)
Arguments
x |
A fitted |
sigma |
Ignored (for compatibility with the generic). |
... |
Not used. |
Value
A named list of covariance matrices (one per grouping factor).
Likelihood-ratio tests between nested hsem models
Description
Likelihood-ratio tests between nested hsem models
Usage
## S3 method for class 'hsem'
anova(object, ..., nsim = 0, seed = NULL, cores = 1L)
Arguments
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. |
Value
A data frame of class anova.
Tidy parameter table
Description
Tidy parameter table
Usage
## S3 method for class 'hsem'
as.data.frame(x, ...)
Arguments
x |
A fitted |
... |
Not used. |
Value
A data frame with all fixed effects and variance parameters.
Confidence intervals
Description
Confidence intervals
Usage
## S3 method for class 'hsem'
confint(
object,
parm,
level = 0.95,
method = c("wald", "boot"),
nsim = 200,
...
)
Arguments
object |
A fitted |
parm |
Ignored (all parameters are returned). |
level |
Confidence level. |
method |
|
nsim |
Bootstrap replicates when |
... |
Passed to |
Value
Data frame of intervals.
Expected product of jointly normal variables
Description
Computes E[\prod_i (\mu_i + e_i)] for e \sim N(0, S) by
Isserlis' theorem. For a two-link path this is the well-known
ab + \sigma_{ab} (Kenny, Korchmaros & Bolger, 2003).
Usage
expected_product(mu, S)
Arguments
mu |
Mean vector. |
S |
Covariance matrix. |
Value
A number.
Examples
expected_product(c(0.5, 0.4), matrix(c(0.1, 0.03, 0.03, 0.2), 2)) # 0.2 + 0.03
Fitted values
Description
Fitted values
Usage
## S3 method for class 'hsem'
fitted(object, type = c("response", "link"), ...)
Arguments
object |
A fitted |
type |
|
... |
Not used. |
Value
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
Description
Extract fixed effects
Usage
## S3 method for class 'hsem'
fixef(object, ...)
Arguments
object |
A fitted |
... |
Not used. |
Value
Named numeric vector; names are response~term.
Fit a hierarchical structural equation model (multilevel path model)
Description
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).
Usage
hsem(
equations,
data,
family = gaussian(),
cov = "unstructured",
dispformula = ~1,
method = NULL,
laplace = FALSE,
hessian = TRUE,
control = list(),
start = NULL
)
Arguments
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 |
Value
An object of class "hsem".
Model
For equation k and observation i in cluster j:
g_k(\mu_{kij}) = x_{kij}'\beta_k + z_{kij}' b_{kj},\qquad
y_{kij} \mid b \sim \mathrm{EF}(\mu_{kij}, \phi_{kij}),
b_j = (b_{1j}', \dots, b_{Kj}')' \sim N(0, \Sigma),\qquad
\log \phi_{kij} = w_{kij}'\gamma_k.
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.
Estimation
Parameters are estimated by the h-likelihood method. For fixed variance
parameters the joint mode of the h-likelihood in (\beta, u) is found
by penalised IRLS (with b = \Lambda(\theta)u, u \sim N(0, I)).
Variance components and dispersion parameters maximise the adjusted profile
h-likelihood: p_u(h) for method = "ML" and p_{\beta,u}(h) 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 p_u(h) (the Laplace approximation to the
marginal likelihood, equivalent to lme4::glmer(nAGQ = 1)), otherwise they
come from the joint mode of h (equivalent to glmer(nAGQ = 0)).
Standard errors of fixed effects come from the inverse of the Hessian of
-h (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().
References
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.
Examples
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")
Parametric bootstrap
Description
Simulates nsim data sets from the fitted model (new random effects,
propagated through the path model) and refits the model to each.
Usage
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"),
...
)
Arguments
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. |
Value
An object of class hsem_boot.
Examples
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)
Within- and between-cluster decomposition (centring within cluster)
Description
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).
Usage
hsem_center(data, vars, cluster, grand = TRUE)
Arguments
data |
A data frame. |
vars |
Character vector of numeric variables. |
cluster |
Name of the cluster variable. |
grand |
If |
Value
data with added columns.
Examples
d <- hsem_center(mlmed, c("x", "m"), "cluster")
head(d)
Check the assumptions of a fitted hierarchical SEM
Description
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:
Usage
hsem_check(
fit,
nsim = 250,
time = NULL,
seed = NULL,
influence = FALSE,
cores = 1L
)
Arguments
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. |
Details
- Level-1 distribution
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.
- Dispersion
Simulation test comparing the observed sum of squared response residuals with its simulated distribution (two-sided).
- Outliers
Binomial test of the number of observations outside the simulation envelope.
- Zero inflation
(Counts and binary data) simulated distribution of the number of zeros.
- Homoscedasticity
Koenker's studentized Breusch-Pagan test against the fitted values and a Brown-Forsythe test across clusters.
- Linearity
F-test of a cubic polynomial of each numeric predictor on the quantile residuals.
- Random effects
Shapiro-Wilk test of the predicted random effects standardized by their marginal SD
\sqrt{\sigma^2 - PEV}.- Serial correlation
(If
timeis given) pooled within-cluster lag-1 autocorrelation of the quantile residuals (Fisher z-test).- Collinearity
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()).
Value
An object of class hsem_check.
References
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.
Cross-validated comparison of linear and neural-network HSEMs
Description
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.
Usage
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,
...
)
Arguments
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 |
Value
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).
Direct, indirect and total effects in a multilevel path model
Description
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. E[a_j b_j] = ab + \sigma_{a_j b_j}
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.
Usage
hsem_effects(
fit,
from,
to,
level = 0.95,
ci = c("montecarlo", "delta"),
nsim = 10000,
seed = NULL
)
Arguments
fit |
A fitted |
from, to |
Variable names (cause and outcome). |
level |
Confidence level. |
ci |
|
nsim |
Monte Carlo draws. |
seed |
Optional seed. |
Details
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).
Value
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.
References
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.
Cluster-deletion influence diagnostics
Description
Refits the model leaving out one cluster at a time and reports Cook's
distance D_j = (\hat\beta - \hat\beta_{(j)})' \hat V^{-1}
(\hat\beta - \hat\beta_{(j)}) / p and the largest scaled change in any fixed
effect (DFBETAS).
Usage
hsem_influence(fit, group = NULL, cores = 1L)
Arguments
fit |
A fitted |
group |
Grouping variable (a column of the data; default: the first grouping factor). |
cores |
Number of forked cores. |
Value
An object of class hsem_influence.
Lag variables within clusters
Description
Creates <var>_lag<k> (value at time t-k 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.
Usage
hsem_lag(data, vars, cluster, time, k = 1L)
Arguments
data |
A data frame. |
vars |
Variables to lag. |
cluster |
Cluster identifier. |
time |
Integer time index. |
k |
Lag order. |
Value
data with added columns.
Examples
d <- hsem_lag(ml2[, c("urge", "dep", "id", "time")], c("urge", "dep"),
"id", "time")
head(d)
Lineup test for visual model checking
Description
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
1/n (for one observer). Reveal the position with lineup_answer().
Usage
hsem_lineup(
fit,
equation = 1,
type = c("resid", "qq", "ranef"),
n = 20,
refit = TRUE,
seed = NULL,
cores = 1L
)
Arguments
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. |
Value
A ggplot object with the answer stored (obfuscated) as an attribute.
References
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.
Neural-network augmented hierarchical SEM
Description
Adds a flexible neural-network component f_k(s) 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.
Usage
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
)
Arguments
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. |
Details
Standard errors of \beta and variance components are
conditional on the estimated network function.
Value
An object of class hsem_nn (with element fit, the final
hsem() fit using the network output as an offset).
References
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.
Examples
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)
nnfit
Partial-dependence plots of the neural-network component
Description
For each network input, plots \bar f(s_v) – 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".
Usage
hsem_nn_pdp(
x,
equation = names(x$nn)[1],
vars = NULL,
grid = 40,
base_size = 11
)
Arguments
x |
An |
equation |
Response whose network is shown. |
vars |
Inputs to show (default: all numeric inputs). |
grid |
Grid size. |
base_size |
Base font size. |
Value
A ggplot object.
hsem colour palette
Description
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).
Usage
hsem_palette()
Value
A named character vector of hex colours.
Examples
hsem_palette()
Caterpillar (forest) plot of cluster-specific coefficients
Description
For every random coefficient, shows the cluster-specific value
\hat\beta + \hat b_j with a 95% prediction interval
(\pm 1.96 times the square root of the prediction error variance),
sorted, against the population average (line) and the 95% range of the
estimated population distribution \hat\beta \pm 1.96\hat\sigma
(band).
Usage
hsem_plot_forest(fit, group = NULL, coefs = NULL, base_size = 11)
Arguments
fit |
A fitted |
group |
Grouping factor (default: the first). |
coefs |
Optional subset of random coefficient names ( |
base_size |
Base font size. |
Value
A ggplot object.
Path diagram of a fitted hierarchical SEM
Description
Draws the path model with its random effects in one of three visual grammars (see Details).
Usage
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
)
Arguments
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. |
Details
-
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
r). -
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
\hat\beta + \hat b_j(colour and width encode sign and size).
Value
A ggplot object.
Examples
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")
Heat map of random-effect correlations
Description
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.
Usage
hsem_plot_recor(fit, group = NULL, base_size = 11)
Arguments
fit |
A fitted |
group |
Grouping factor (default: the first). |
base_size |
Base font size. |
Value
A ggplot object.
Distribution of cluster-specific path coefficients
Description
Draws, for each random coefficient, the estimated population distribution
N(\hat\beta, \hat\sigma^2) of cluster-specific values, the
predicted values of the observed clusters (dots), and the estimated share
of clusters with a positive coefficient \Phi(\hat\beta/\hat\sigma).
Usage
hsem_plot_ridge(fit, group = NULL, coefs = NULL, base_size = 11)
Arguments
fit |
A fitted |
group |
Grouping factor (default: the first). |
coefs |
Optional subset of random coefficient names ( |
base_size |
Base font size. |
Value
A ggplot object.
Simulation-based power analysis over numbers of clusters
Description
Simulation-based power analysis over numbers of clusters
Usage
hsem_power(
J,
nrep,
generate,
fit,
parameter,
truth,
extract = .default_extract,
alpha = 0.05,
seed = NULL,
cores = 1L
)
Arguments
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 |
Value
An object of class hsem_power.
Marginal and conditional R-squared and ICC per equation
Description
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 \pi^2/3, probit 1,
cloglog \pi^2/6, Poisson-log \log(1 + 1/\lambda) (log-normal
approximation), Gamma-log \psi_1(1/\phi) (trigamma).
Usage
hsem_r2(fit)
Arguments
fit |
A fitted |
Value
Data frame with fixed, random and residual variances, marginal and
conditional R^2, and the adjusted ICC.
References
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
Description
Refit an hsem model to new data
Usage
hsem_refit(fit, data, hessian = FALSE, warm = TRUE, ...)
Arguments
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. |
Value
A fitted hsem object.
Simulate multilevel mediation data with random paths
Description
Generates x \rightarrow m \rightarrow y 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()).
Usage
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
)
Arguments
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. |
Details
Model: m_{ij} = \alpha_{mj} + a_j x_{ij} + e^m_{ij},
y_{ij} = \alpha_{yj} + b_j m_{ij} + c'_j x_{ij} + g(z_{ij}) + e^y_{ij}
with (\alpha_{mj}-\alpha_m, a_j - a, \alpha_{yj}-\alpha_y, b_j - b,
c'_j - c') \sim N(0, \Sigma). The population average indirect effect is
ab + \sigma_{ab}.
Value
A data frame with attribute "truth" (true parameters, including
the average indirect effect).
Examples
d <- hsem_sim_mediation(J = 30, nj = 10, seed = 1)
attr(d, "truth")$indirect
Simulate a bivariate multilevel VAR(1) (dynamic SEM) panel
Description
Person-specific means, autoregressive and cross-lagged coefficients:
y_{it} - \mu_i = \Phi_i (y_{i,t-1} - \mu_i) + e_{it}. This is the
data-generating model behind the ml2 example (urge to smoke and
depression). Clusters whose \Phi_i is not stationary are redrawn.
Usage
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
)
Arguments
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. |
Value
Long data frame with id, time, the two series and their within-
person lags (<name>_lag1).
Monte Carlo simulation study with performance measures and Monte Carlo SEs
Description
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).
Usage
hsem_simstudy(
nrep,
generate,
fit,
truth,
extract = .default_extract,
alpha = 0.05,
seed = NULL,
cores = 1L,
progress = FALSE
)
Arguments
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. |
Value
An object of class hsem_simstudy.
References
Morris, T. P., White, I. R. and Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38, 2074–2102.
Examples
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)
Fit a model with the hsem 1.0 interface (deprecated wrapper around hsem())
Description
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.
Usage
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
)
Arguments
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 |
Value
A fitted hsem object.
Model specification in the hsem 1.0 style (deprecated)
Description
Kept so that scripts written for hsem 1.0 still run. New code should use
hsem() directly.
Usage
hsemmodeling(
Model = "mean",
Link = NULL,
LinPred = "constant",
RandDist = NULL,
Offset = NULL,
LMatrix = NULL,
LinkRandVariance = NULL,
LinPredRandVariance = NULL,
RandDistRandVariance = "gaussian",
LinkRandVariance2 = NULL,
LinPredRandVariance2 = NULL
)
Arguments
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 ( |
Value
An object of class hsemmodeling.
Reveal the position of the observed data in a lineup
Description
Reveal the position of the observed data in a lineup
Usage
lineup_answer(lineup)
Arguments
lineup |
A plot returned by |
Value
The panel number (integer).
Simulated urge-to-smoke diary data (example from hsem 1.0)
Description
A simulated subset following the urge-to-smoke example of McNeish and Hamaker (2020): 20 persons with 10 equally spaced occasions each.
Usage
ml2
Format
A data frame with 200 rows and 6 variables:
- urge
standardized urge to smoke
- urge1
urge at the previous occasion (lag 1)
- dep
standardized depression
- dep1
depression at the previous occasion (lag 1)
- id
person identifier
- time
occasion (1–10)
Note
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.
Source
Simulated; originally distributed with the CRAN package hsem 1.0.
References
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.
Simulated multilevel mediation data with random paths
Description
Generated by hsem_sim_mediation() (see data-raw/make_data.R) with 50
clusters of 20 observations: a = 0.5, b = 0.4, c' = 0.2,
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 0.5 \times 0.4 + 0.5 \times
0.35 \times 0.3 = 0.2525. z1, z2 enter y nonlinearly through
g(z) (column g_true).
Usage
mlmed
Format
A data frame with 1000 rows: cluster, x, m, y, z1, z2,
g_true.
Source
Simulated.
Build a neural network
Description
Build a neural network
Usage
nn_build(
d_in,
architecture = c("mlp", "resnet", "glu", "linear"),
hidden = c(32, 16),
activation = "relu",
dropout = 0
)
Arguments
d_in |
Number of inputs. |
architecture |
|
|
Hidden-layer widths. | |
activation |
|
dropout |
Dropout rate after each hidden layer (training only). |
Value
A network object (list).
Network component values
Description
Network component values
Usage
nn_component(
object,
newdata = NULL,
equation = names(object$nn)[1],
members = FALSE
)
Arguments
object |
An |
newdata |
Data frame (defaults to the training data). |
equation |
Response name. |
members |
Return the matrix of ensemble members instead of the mean. |
Value
Numeric vector (or matrix) of centred network outputs f(s).
Plot a fitted hierarchical SEM
Description
Convenience dispatcher to the hsem graphics.
Usage
## S3 method for class 'hsem'
plot(
x,
type = c("path", "twolevel", "clusters", "forest", "ridge", "recor", "diagnostics"),
...
)
Arguments
x |
A fitted |
type |
One of |
... |
Passed to the underlying function ( |
Value
A ggplot / patchwork object.
Examples
fit <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)),
data = mlmed)
plot(fit)
plot(fit, "ridge")
Diagnostic dashboard
Description
Diagnostic dashboard
Usage
## S3 method for class 'hsem_check'
plot(x, equation = 1, which = "all", base_size = 11, ...)
Arguments
x |
An |
equation |
Equation (name or index). |
which |
Panels to show: any of |
base_size |
Base font size. |
... |
Not used. |
Value
A patchwork object.
Plot direct, indirect and total effects
Description
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.
Usage
## S3 method for class 'hsem_effects'
plot(x, base_size = 11, ...)
Arguments
x |
An |
base_size |
Base font size. |
... |
Not used. |
Value
A patchwork/ggplot object.
Plot simulation-study performance
Description
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 |z|.
Usage
## S3 method for class 'hsem_simstudy'
plot(x, type = c("performance", "zip"), parameter = NULL, base_size = 11, ...)
Arguments
x |
An |
type |
|
parameter |
Parameter for the zip plot (default: the first). |
base_size |
Base font size. |
... |
Not used. |
Value
A ggplot / patchwork object.
Predictions from an hsem fit
Description
Predictions from an hsem fit
Usage
## S3 method for class 'hsem'
predict(
object,
newdata = NULL,
type = c("response", "link"),
re = c("conditional", "marginal"),
...
)
Arguments
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. |
Value
Named list per equation (a vector for single-equation models).
Predictions from an NN-augmented hsem
Description
Predictions from an NN-augmented hsem
Usage
## S3 method for class 'hsem_nn'
predict(
object,
newdata = NULL,
type = c("response", "link"),
re = c("conditional", "marginal"),
...
)
Arguments
object |
An |
newdata |
Data frame. |
type |
|
re |
|
... |
Not used. |
Value
Named list per equation (vector for single-equation models).
Conditional modes (BLUPs) of the random effects
Description
Conditional modes (BLUPs) of the random effects
Usage
## S3 method for class 'hsem'
ranef(object, condVar = FALSE, ...)
Arguments
object |
A fitted |
condVar |
Attach the prediction-error covariance array ( |
... |
Not used. |
Value
A named list (one matrix per grouping factor; rows = levels).
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
Residuals of an hsem fit
Description
Residuals of an hsem fit
Usage
## S3 method for class 'hsem'
residuals(object, type = c("response", "pearson", "deviance", "quantile"), ...)
Arguments
object |
A fitted |
type |
|
... |
Not used. |
Value
Named list per equation (vector for a single equation). All types are conditional on the predicted random effects.
References
Dunn, P. K. and Smyth, G. K. (1996). Randomized quantile residuals. J. Comput. Graph. Stat., 5, 236–244.
Simulate responses from a fitted hsem
Description
Simulate responses from a fitted hsem
Usage
## S3 method for class 'hsem'
simulate(
object,
nsim = 1,
seed = NULL,
re = c("new", "conditional"),
propagate = TRUE,
...
)
Arguments
object |
A fitted |
nsim |
Number of simulated data sets. |
seed |
Optional seed. |
re |
|
propagate |
If |
... |
Not used. |
Value
A list of nsim data frames.
Simulated intensive-longitudinal (EMA) data: urge to smoke and depression
Description
Bivariate multilevel VAR(1) generated by hsem_sim_var1() (see
data-raw/make_data.R): 80 persons, 40 occasions, average lag matrix
\Phi = [0.40, 0.15; 0.10, 0.30] (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.
Usage
smoke_ema
Format
A data frame with 3200 rows: id, time, urge, dep,
urge_lag1, dep_lag1 (lags are NA at the first occasion).
Source
Simulated.
Summarise an hsem fit
Description
Summarise an hsem fit
Usage
## S3 method for class 'hsem'
summary(object, level = 0.95, ...)
Arguments
object |
A fitted |
level |
Confidence level for intervals. |
... |
Not used. |
Value
An object of class summary.hsem.
ggplot2 theme for hsem graphics
Description
ggplot2 theme for hsem graphics
Usage
theme_hsem(base_size = 11, base_family = "", grid = "xy")
Arguments
base_size |
Base font size. |
base_family |
Font family. |
grid |
|
Value
A ggplot2 theme.