hsemx: extended hierarchical structural equation models

Rezzy Eko Caraka

2026-11-09

library(hsemx)

About. hsemx (hsem extended) is an extended, re-engineered successor of the CRAN package hsem 1.0 (Caraka, Noh & Lee, 2021), building on the hierarchical-likelihood SEM of Caraka et al. (2021, 2022) and their h-likelihood work in machine learning and software (Caraka et al., 2020, 2022; see References). It keeps the h-likelihood framework and the function name hsem(), but replaces the estimation engine and adds estimated cross-equation random-effect covariances, indirect effects with random slopes, neural-network components, path diagrams with random effects, assumption diagnostics, and simulation tools. Because it is a separate package, hsem and hsemx can be installed side by side; load only one of them in a session, since both export hsem().

1. The model

A hierarchical structural equation model (HSEM) is a recursive system of (generalized) linear mixed models. For equation \(k\), observation \(i\) and cluster \(j\)

\[g_k(\mu_{kij}) = x_{kij}^\top\beta_k + z_{kij}^\top b_{kj},\qquad y_{kij}\mid b \sim \text{EF}(\mu_{kij},\phi_{kij}),\qquad \log\phi_{kij} = w_{kij}^\top\gamma_k ,\]

and the random coefficients of all equations that share a grouping factor are stacked, \(b_j = (b_{1j}^\top,\dots,b_{Kj}^\top)^\top \sim N(0,\Sigma)\). The covariance matrix \(\Sigma\) links the equations: for instance, the covariance between the random \(a\)-path (\(x\to m\)) and the random \(b\)-path (\(m\to y\)) of a multilevel mediation model. Given \(b\), the responses of different equations are independent, so endogenous variables can be used as predictors of later equations.

Estimation uses the h-likelihood \(h = \log f(y\mid u) + \log f(u)\) with \(b = \Lambda(\theta)u\), \(u\sim N(0,I)\):

For Gaussian identity-link equations these are the exact ML/REML likelihoods; otherwise they are Laplace approximations computed with the observed information (identical to glmmTMB’s Laplace approximation when laplace = TRUE). The package test suite checks the estimates against lme4, nlme and glmmTMB.

2. Multilevel mediation with random paths

mlmed holds 50 clusters × 20 observations generated with \(a=0.5\), \(b=0.4\), \(c'=0.2\) and correlated random \(a\)- and \(b\)-paths (true average indirect effect 0.2525).

fit <- hsem(list(m ~ x + (1 + x | cluster),
                 y ~ m + x + (1 + m + x | cluster)),
            data = mlmed)
summary(fit)
#> -- Hierarchical Structural Equation Model --------------------------------
#>  Estimation  : h-likelihood, REML (exact)
#>  Observations: 2000  [m: 1000, y: 1000]
#>  Grouping    : cluster      50 levels, 5 random coefficient(s), unstructured
#>  Converged   : yes   (11.6 s)
#>  -2 logLik (REML) : 6654.508   AIC: --   BIC: --
#>  cAIC: 6506.49   (effective df rho = 141.75)
#> 
#> -- Equation 1: m ~ x   [gaussian, link = identity] -----------------------
#>             Estimate Std.Error z value Pr(>|z|)    
#> (Intercept) -0.01798   0.09220  -0.195    0.845    
#> x            0.50537   0.06151   8.216   <2e-16 ***
#> 
#> -- Equation 2: y ~ m + x   [gaussian, link = identity] -------------------
#>             Estimate Std.Error z value Pr(>|z|)    
#> (Intercept) -0.33711   0.10074  -3.346 0.000819 ***
#> m            0.42874   0.05782   7.414 1.22e-13 ***
#> x            0.21991   0.05787   3.800 0.000145 ***
#> 
#> -- Variance components (SD scale; correlations) --------------------------
#>  Group    Parameter                         Estimate SE     95% CI         
#>  cluster  sd(m:(Intercept))                 0.6086   0.0706 [0.485, 0.764] 
#>  cluster  sd(m:x)                           0.3632   0.0523 [0.274, 0.482] 
#>  cluster  sd(y:(Intercept))                 0.6326   0.0822 [0.490, 0.816] 
#>  cluster  sd(y:m)                           0.2924   0.0571 [0.199, 0.429] 
#>  cluster  sd(y:x)                           0.2120   0.0819 [0.099, 0.452] 
#>  cluster  cor(m:(Intercept), m:x)           0.1581   0.1791 [-0.198, 0.477]
#>  cluster  cor(m:(Intercept), y:(Intercept)) -0.0027  0.1807 [-0.342, 0.338]
#>  cluster  cor(m:(Intercept), y:m)           0.0384   0.2095 [-0.356, 0.422]
#>  cluster  cor(m:(Intercept), y:x)           -0.2443  0.2848 [-0.687, 0.331]
#>  cluster  cor(m:x, y:(Intercept))           -0.2222  0.1899 [-0.549, 0.164]
#>  cluster  cor(m:x, y:m)                     0.5884   0.1962 [0.087, 0.852] 
#>  cluster  cor(m:x, y:x)                     0.1475   0.3566 [-0.512, 0.698]
#>  cluster  cor(y:(Intercept), y:m)           0.1471   0.2222 [-0.289, 0.532]
#>  cluster  cor(y:(Intercept), y:x)           -0.1342  0.3164 [-0.645, 0.459]
#>  cluster  cor(y:m, y:x)                     -0.6023  0.2805 [-0.915, 0.165]
#>  Residual residual variance (m)             1.0660   0.0502 [0.972, 1.169] 
#>  Residual residual variance (y)             1.8609   0.0889 [1.695, 2.044] 
#> 
#> -- Variance explained (Nakagawa-Johnson-Schielzeth) ----------------------
#>  Equation             Family R2 marginal R2 conditional ICC adj.
#>         m gaussian(identity)       0.142          0.418    0.322
#>         y gaussian(identity)       0.169          0.362    0.232
#> 
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> Wald z-tests; CIs for SDs on the log scale and for correlations on the
#> Fisher-z scale. With few clusters prefer hsem_boot().

The average indirect effect over clusters is \(E[a_jb_j] = ab + \sigma_{a_j b_j}\) (Kenny, Korchmaros & Bolger, 2003):

eff <- hsem_effects(fit, from = "x", to = "y", seed = 1)
eff
#> -- Effects of x on y -----------------------------------------------------
#>          Effect Estimate     SE 95% CI (Monte Carlo) a*b... + cov part P(>0)
#>     x -> m -> y   0.2792 0.0528     [0.1857, 0.3927] 0.2167     0.0625 0.897
#>          x -> y   0.2199 0.0578     [0.1061, 0.3327] 0.2199     0.0000 0.850
#>  TOTAL INDIRECT   0.2792 0.0528     [0.1857, 0.3927]     NA         NA    NA
#>          DIRECT   0.2199 0.0578     [0.1061, 0.3327]     NA         NA    NA
#>           TOTAL   0.4991 0.0689     [0.3679, 0.6390]     NA         NA    NA
#> 
#> 'a*b...' = product of fixed path coefficients; '+ cov part' = contribution of
#> random-slope covariances; P(>0) = share of clusters whose path effect is positive.
plot(eff)

3. Seeing the random effects: alternative path diagrams

Classic. Arrows carry the fixed paths; a black dot on an arrow marks a random slope (with its SD across clusters); circles mark random intercepts; dashed violet curves are significant random-effect correlations.

hsem_plot_path(fit)

Two-level. The multilevel-SEM depiction: each random coefficient is a latent between-cluster variable pointing at the intercept or slope it modifies.

hsem_plot_path(fit, style = "twolevel")

Cluster-specific path models, chosen to span the distribution of the cluster-specific indirect effect:

hsem_plot_path(fit, style = "clusters")

Distributions of the random paths, including the share of clusters whose path is positive, \(\Phi(\hat\beta/\hat\sigma)\):

hsem_plot_ridge(fit)

Caterpillar plot with prediction intervals, and the random-effect correlation matrix:

hsem_plot_forest(fit)

hsem_plot_recor(fit)

4. Checking the assumptions

hsem_check() computes randomized quantile residuals, simulation-based scaled residuals, standardized BLUPs, and a battery of tests; plot() draws the dashboard for one equation.

chk <- hsem_check(fit, nsim = 200, seed = 1)
chk
#> -- Assumption checks -----------------------------------------------------
#>  Equation Assumption            Test                                  
#>  m        Level-1 distribution  Shapiro-Wilk (quantile residuals)     
#>  m        Level-1 distribution  KS uniformity (simulated residuals)   
#>  m        Dispersion            Simulation test (ratio obs/sim)       
#>  m        Outliers              Binomial (outside envelope)           
#>  m        Homoscedasticity      Breusch-Pagan (Koenker) vs fitted     
#>  m        Homoscedasticity      Brown-Forsythe across clusters        
#>  m        Linearity             Cubic trend of residuals in x         
#>  m        Normal random effects Shapiro-Wilk, Intercept of m (cluster)
#>  m        Normal random effects Shapiro-Wilk, x <U+2192> m (cluster)  
#>  y        Level-1 distribution  Shapiro-Wilk (quantile residuals)     
#>  y        Level-1 distribution  KS uniformity (simulated residuals)   
#>  y        Dispersion            Simulation test (ratio obs/sim)       
#>  y        Outliers              Binomial (outside envelope)           
#>  y        Homoscedasticity      Breusch-Pagan (Koenker) vs fitted     
#>  y        Homoscedasticity      Brown-Forsythe across clusters        
#>  y        Linearity             Cubic trend of residuals in m         
#>  y        Linearity             Cubic trend of residuals in x         
#>  y        Collinearity          max VIF (m)                           
#>  y        Normal random effects Shapiro-Wilk, Intercept of y (cluster)
#>  y        Normal random effects Shapiro-Wilk, m <U+2192> y (cluster)  
#>  y        Normal random effects Shapiro-Wilk, x <U+2192> y (cluster)  
#>  Statistic p      Verdict
#>  0.999     0.8552 ok     
#>  0.021     0.7699 ok     
#>  0.925     0.1100 ok     
#>  6.000     0.2629 ok     
#>  0.637     0.4250 ok     
#>  0.987     0.4994 ok     
#>  0.793     0.4980 ok     
#>  0.990     0.9470 ok     
#>  0.981     0.5881 ok     
#>  0.997     0.0632 ok     
#>  0.031     0.2917 ok     
#>  0.932     0.1400 ok     
#>  5.000     0.1479 ok     
#>  6.732     0.0095 check  
#>  0.987     0.5012 ok     
#>  1.157     0.3251 ok     
#>  0.279     0.8409 ok     
#>  1.188            ok     
#>  0.978     0.4840 ok     
#>  0.972     0.2903 ok     
#>  0.963     0.1196 ok     
#> 
#> Simulation-based tests use 200 data sets simulated from the fitted model
#> (conditional on the predicted random effects). No multiplicity correction.
plot(chk, equation = "y")

Visual inference. In a lineup (Buja et al., 2009) the real residual plot is hidden among plots of data simulated from the fitted model and refitted. If you can spot it, the model is rejected at level 1/20.

lu <- hsem_lineup(fit, equation = "y", type = "resid", seed = 7)
lu
lineup_answer(lu)

Cluster influence by leave-one-cluster-out refits:

infl <- hsem_influence(fit)
plot(infl)

5. Dynamic SEM: cross-lagged panel with random effects

smoke_ema contains 80 persons × 40 occasions of urge to smoke and depression. A two-level cross-lagged model with person-specific means, autoregressive and cross-lagged effects:

ema <- hsem_center(subset(smoke_ema, time > 1), c("urge_lag1", "dep_lag1"), "id")
dsem <- hsem(list(urge ~ urge_lag1_cw + dep_lag1_cw + (1 + urge_lag1_cw | id),
                  dep  ~ urge_lag1_cw + dep_lag1_cw + (1 + dep_lag1_cw  | id)),
             data = ema)
summary(dsem)
#> -- Hierarchical Structural Equation Model --------------------------------
#>  Estimation  : h-likelihood, REML (exact)
#>  Observations: 6240  [urge: 3120, dep: 3120]
#>  Grouping    : id           80 levels, 4 random coefficient(s), unstructured
#>  Converged   : yes   (9.7 s)
#>  -2 logLik (REML) : 16959.792   AIC: --   BIC: --
#>  cAIC: 16623.79   (effective df rho = 213.44)
#> 
#> -- Equation 1: urge ~ urge_lag1_cw + dep_lag1_cw   [gaussian, link = identity] ---
#>               Estimate Std.Error z value Pr(>|z|)    
#> (Intercept)  -0.001751  0.073614  -0.024    0.981    
#> urge_lag1_cw  0.351571  0.022385  15.706  < 2e-16 ***
#> dep_lag1_cw   0.137569  0.023190   5.932 2.99e-09 ***
#> 
#> -- Equation 2: dep ~ urge_lag1_cw + dep_lag1_cw   [gaussian, link = identity] ---
#>               Estimate Std.Error z value Pr(>|z|)    
#> (Intercept)  -0.003524  0.060183  -0.059    0.953    
#> urge_lag1_cw  0.123615  0.014140   8.742   <2e-16 ***
#> dep_lag1_cw   0.264275  0.023354  11.316   <2e-16 ***
#> 
#> -- Variance components (SD scale; correlations) --------------------------
#>  Group    Parameter                                Estimate SE    
#>  id       sd(urge:(Intercept))                     0.6380   0.0541
#>  id       sd(urge:urge_lag1_cw)                    0.1185   0.0242
#>  id       sd(dep:(Intercept))                      0.5229   0.0441
#>  id       sd(dep:dep_lag1_cw)                      0.1293   0.0229
#>  id       cor(urge:(Intercept), urge:urge_lag1_cw) 0.0286   0.1910
#>  id       cor(urge:(Intercept), dep:(Intercept))   0.1713   0.1162
#>  id       cor(urge:(Intercept), dep:dep_lag1_cw)   0.2537   0.1725
#>  id       cor(urge:urge_lag1_cw, dep:(Intercept))  -0.2102  0.1792
#>  id       cor(urge:urge_lag1_cw, dep:dep_lag1_cw)  0.1031   0.2698
#>  id       cor(dep:(Intercept), dep:dep_lag1_cw)    0.3415   0.1700
#>  Residual residual variance (urge)                 1.0311   0.0268
#>  Residual residual variance (dep)                  0.6389   0.0166
#>  95% CI         
#>  [0.540, 0.753] 
#>  [0.079, 0.177] 
#>  [0.443, 0.617] 
#>  [0.091, 0.183] 
#>  [-0.333, 0.383]
#>  [-0.062, 0.387]
#>  [-0.102, 0.552]
#>  [-0.523, 0.153]
#>  [-0.406, 0.564]
#>  [-0.021, 0.625]
#>  [0.980, 1.085] 
#>  [0.607, 0.672] 
#> 
#> -- Variance explained (Nakagawa-Johnson-Schielzeth) ----------------------
#>  Equation             Family R2 marginal R2 conditional ICC adj.
#>      urge gaussian(identity)       0.121          0.377    0.292
#>       dep gaussian(identity)       0.092          0.373    0.309
#> 
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> Wald z-tests; CIs for SDs on the log scale and for correlations on the
#> Fisher-z scale. With few clusters prefer hsem_boot().

Lagged predictors are centred within persons so that the lag effects are within-person effects. With observed person means the autoregressive effect has the usual Nickell bias of order \(1/T\).

hsem_plot_path(dsem, show_cor = "all")

6. Non-Gaussian outcomes

db <- hsem_sim_mediation(J = 60, nj = 25, family_y = "binomial", seed = 11)
fb <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 | cluster)),
           data = db, family = list(m = "gaussian", y = binomial()), laplace = TRUE)
summary(fb)$coefficients
#>   equation        term    estimate  std.error  statistic      p.value
#> 1        m (Intercept) -0.06635967 0.06195509 -1.0710930 2.841276e-01
#> 2        m           x  0.48457058 0.04509662 10.7451640 6.245081e-27
#> 3        y (Intercept) -0.03512062 0.09010714 -0.3897651 6.967102e-01
#> 4        y           m  0.38205074 0.05698706  6.7041664 2.025594e-11
#> 5        y           x  0.19155211 0.06209394  3.0848763 2.036368e-03
#>      conf.low  conf.high
#> 1 -0.18778942 0.05507009
#> 2  0.39618283 0.57295833
#> 3 -0.21172737 0.14148613
#> 4  0.27035815 0.49374332
#> 5  0.06985023 0.31325399

Effects through a non-identity link are reported on the linear-predictor scale (with a warning), because a product of coefficients is not a causal indirect effect on the probability scale.

7. Neural-network components

hsem_nn() adds a neural network \(f(s)\) to selected equations while keeping the linear paths and the random effects. Architectures: "mlp", "resnet" (residual blocks), "glu" (gated linear units) and "ensemble" (deep ensemble).

nnfit <- hsem_nn(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)),
                 data = mlmed, nn = list(y = ~ z1 + z2), architecture = "resnet",
                 hidden = c(32, 32, 32), epochs = 80, seed = 1)
round(fixef(nnfit$fit), 3)
#> m~(Intercept)           m~x y~(Intercept)           y~m           y~x 
#>        -0.018         0.505        -0.342         0.426         0.217
cor(nn_component(nnfit), nnfit$data$g_true)
#> [1] 0.9662423
hsem_nn_pdp(nnfit)

Cross-validated comparison of the architectures (held-out clusters):

cv <- hsem_cv(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)),
              data = mlmed, nn = list(y = ~ z1 + z2), cluster = "cluster",
              architectures = c("linear", "mlp", "resnet", "glu", "ensemble"),
              folds = 5, seed = 1)
cv
plot(cv)

8. Simulation studies and power

ss <- hsem_simstudy(
  nrep = 30,
  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
#> -- Monte Carlo simulation study ------------------------------------------
#>  Replications: 30 (failed: 0)
#> 
#>  Parameter Truth          Bias         EmpSE ModSE relerr %          RMSE
#>        m~x   0.5 0.006 (0.013) 0.069 (0.009)    21.3 (16.2) 0.068 (0.008)
#>        y~m   0.4 0.016 (0.013) 0.071 (0.009)     8.7 (14.6) 0.072 (0.009)
#>        y~x   0.2 0.025 (0.011) 0.058 (0.008)    15.2 (15.2) 0.062 (0.008)
#>       Coverage     Rejection
#>  1.000 (0.000) 1.000 (0.000)
#>  0.933 (0.046) 1.000 (0.000)
#>  0.933 (0.046) 0.967 (0.033)
#> 
#> Values in parentheses are Monte Carlo standard errors (Morris et al., 2019).
plot(ss)

plot(ss, type = "zip", parameter = "y~m")

Simulation-based power over the number of clusters:

pw <- hsem_power(J = c(10, 20, 40, 80), nrep = 200,
                 generate = function(J) hsem_sim_mediation(J = J, nj = 10, b = 0.2),
                 fit = function(d) hsem(list(m ~ x + (1 + x | cluster),
                                             y ~ m + x + (1 + m | cluster)), d),
                 parameter = "y~m", truth = c("y~m" = 0.2), seed = 1)
plot(pw)

9. Migrating from hsem 1.0 (CRAN)

hsemfit() and hsemmodeling() still work as wrappers around hsem(). Note that in hsem 1.0 a term (x | id) denoted a single random slope; the wrapper translates it to (0 + x | id). Random effects in dispersion models and non-normal random effects are not available in 2.x.

References

h-likelihood and HSEM work of the author

Methodology