Learn R Programming

metaSEM (version 2.0)

sem: Fit a structural equation model using OpenMx

Description

Variable names, raw data column names, and ordinary parameter labels must not contain periods. Rename consistently, e.g., x.1 to x_1, and check for duplicate names. Definition-variable references such as data.x_1 and group or cluster values containing periods are allowed.

It fits a structural equation model by creating a mxModel from a RAM object.

Usage

sem(model.name = "sem", RAM = NULL, data = NULL,
    Cov = NULL, means = NULL, numObs, intervals.type = c("z",
        "LB"), startvalues = NULL, lbound = NULL, ubound = NULL,
    replace.constraints = FALSE, mxModel.Args = NULL,
    run = TRUE, silent = TRUE, group = NULL, cluster = NULL,
    ...)
create.mxModel(model.name = "sem", RAM = NULL, data = NULL,
    Cov = NULL, means = NULL, numObs, intervals.type = c("z",
        "LB"), startvalues = NULL, replace.constraints = FALSE,
    mxModel.Args = NULL, run = TRUE, silent = TRUE,
    ...)

Value

An object of class mxsem

Arguments

model.name

A string for the model name in mxModel.

RAM

A RAM object including a list of matrices of the model returned from lavaan2RAM.

data

A data frame or matrix of data.

Cov

If data=NULL, a covariance matrix for a single-level model, a list of matrices (one per group) for a multiple-group model, or a list of matrices (one per cluster) for a two-level model. For a combined group and two-level model, supply a list of groups, each containing a list of cluster covariance matrices. Matrices must have named variables and use the usual unbiased covariance denominator n-1. For two-level summary input, covariance reconstruction is checked in each variable's scale; incompatible matrices are rejected. When group or cluster names are supplied on both Cov and means or numObs, entries are matched by name; names must be complete, unique, and consistent. Unnamed entries are matched by position.

means

Means corresponding to Cov: a named vector for a single-level model, a list of vectors for multiple groups or clusters, or a nested list for combined group and two-level models. Means are required for two-level summary input. For single-level and multiple-group input they are optional; omitted means remove the mean structure.

numObs

Sample sizes corresponding to Cov: a scalar for a single-level model, a vector for multiple groups or clusters, or a list of vectors for combined group and two-level models.

intervals.type

Either z (default if missing) or LB. If it is z, it calculates the 95% confidence intervals (CIs) based on the estimated standard error. If it is LB, it calculates the 95% likelihood-based CIs on the parameter estimates.

startvalues

A list of named starting values of the free parameters, e.g., list(a=1, b=2)

lbound

A list of lower bound of the free parameters. If it is not provided, all free parameters are assumed NA. Bounds from inequalities in the lavaan syntax, recorded by lavaan2RAM, are also applied; a bound given here for the same parameter takes precedence. Bounds must be named and refer to model parameters. Bounds on substituted expressions remain constraints; definition-variable substitutions with bounds are unsupported.

ubound

A list of upper bound of the free parameters. If it is not provided, all free parameters are assumed NA. Bounds from the lavaan syntax are handled as for lbound.

replace.constraints

Logical. If TRUE, the parameters on the left hand side will be replaced by the constraints on the right hand side. That is, the parameters on the left hand side are no longer parameters in the model.

mxModel.Args

A list of arguments passed to mxModel.

run

Logical. If FALSE, only return the mx model without running the analysis.

silent

Logical. Passed to mxRun. If FALSE, warnings and errors during the mxTryHard() retries are also printed as messages. A fit that ends with an OpenMx status code other than 0 or 1 is retried once with mxTryHard from its estimates; a warning is given if the status code is still neither 0 nor 1.

group

For combined group and cluster summary inputs, group and cluster must name different columns. A character string naming the column in data identifying group membership. Required when RAM is a multiple-group RAM object, i.e., created by lavaan2RAM with ngroups > 1. data must be a single data frame in this case; it is split internally by the unique values of data[[group]] in first-appearance order in the data (not sorted, and not a factor's own levels() order, even for a factor column -- this matches how lavaan itself numbers groups), which must correspond, in order, to the groups used when the model was specified (e.g., lavaan's c(...) syntax numbers groups the same way, and so do group: blocks, in their order in the syntax rather than by their labels). A warning is given when the labels of group: blocks are the values of data[[group]] in a different order. A group value that is not itself a legal mxModel name (e.g. purely numeric, or containing a character such as . or -) is sanitized into one internally; the resulting submodel names are available via names(fit$mx.fit@submodels), and a mapping back to the original data values via fit$group.map, so plot.mxsem's own group argument can still be called with the original, unsanitized group value. An unused factor level in data[[group]] (one that never actually occurs in the data) is simply never treated as a group in the first place (this is what first-appearance order, above, naturally does); if that leaves fewer groups than RAM expects, it is reported as a group-count mismatch. Cov/numObs input is supported with one covariance matrix and sample size per group. replace.constraints=TRUE is supported (substituting a constraint into whichever group's A/S/ M matrices contain it, including a constraint that spans multiple groups, e.g. constraining one group's variance to be a multiple of another's); a definition variable (data.*) inside such a constraint resolves against whichever group's own data it is used in, since (unlike two-level's between level) every group already carries its own full data slice.

cluster

A character string naming the column in data identifying cluster membership. It is required when RAM is a two-level RAM object, i.e., created by lavaan2RAM from lavaan's two-level (level: 1 / level: 2) syntax; data must then be a single data frame of individual-level (level-1) rows. In a single-level or flat multiple-group model, it records the independent units for cluster-robust standard errors in summary(fit, robust=TRUE) and vcov(fit, robust=TRUE); the fitted likelihood and estimates do not change, and raw data are required. See Details.

...

Further arguments will be passed to either mxRun or mxTryHard

Author

Mike W.-L. Cheung <[email protected]>

Details

Two-level models. A manifest variable appearing at both levels is internally split into within and between components. Consequently, a level-1 regression uses only the predictor's within component, as in lavaan. Two-level summary input requires separate means, covariance matrices, and sample sizes for each cluster; a pooled covariance matrix cannot identify within- and between-cluster variation. For complete Gaussian data these summaries reproduce the raw-data likelihood. Combined group and two-level models use nested group:/level: lavaan syntax and both group and cluster arguments. replace.constraints=TRUE is supported for two-level models (substituting a constraint into whichever of the within-/between-level A/S/M matrices contains it, including a constraint that spans both levels); a definition variable (data.*) may be used in such a constraint at either level if its between-level values are constant within each cluster. Cluster-level observed covariates likewise require a constant value within each cluster. The reported number of observations and the information criteria use the number of level-1 rows with at least one observed level-1 variable, as in lavaan. A cluster with a measured between-level variable still contributes, even if all its level-1 data are missing.

Constraints. Models with constraints between parameters (==, <, or >) are fitted with an OpenMx feasibility tolerance of 1e-6 unless one has been set with mxOption(), and their model-based standard errors are computed from the Hessian of the Lagrangian of -2LL and the constraints that hold at the estimates instead of being taken from OpenMx. They equal those of the same model with the constraints substituted (replace.constraints=TRUE); for nonlinear constraints they can differ from lavaan's, which omit the curvature of the constraints.

Robust standard errors. With a single-level model and no cluster, robust covariance uses the observation-level sandwich of OpenMx's imxRobustSE(), whose meat is multiplied by \(N/(N-1)\). With cluster, it sums the row scores within clusters before forming the sandwich and multiplies the meat by \(G/(G-1)\), where \(G\) is the number of clusters, as lavaan does for single-group models; this allows within-cluster dependence. With one row per cluster it equals the robust covariance without cluster. For flat multiple-group models, the same cluster ID in different groups denotes the same independent unit; use distinct IDs when groups contain distinct clusters. The bread uses the observed information, so it matches lavaan with information="observed"; lavaan's default for cluster=, the expected information, can give much smaller standard errors with data missing at random (see clusterRobustSE). The optional smallSample=TRUE in summary() or vcov() also multiplies the meat by \((N-1)/(N-p)\), where \(N\) is the number of rows and \(p\) the number of free parameters (including those determined by constraints or at a bound), for a total factor of \(G/(G-1) \cdot (N-1)/(N-p)\). With few independent clusters, summary(fit, robust=TRUE, t.df=) uses a \(t\) reference distribution instead of \(z\); see summary for how to choose its degrees of freedom. Row scores are computed by numerical differentiation of the row likelihoods, so their cost hardly depends on the number of rows. Parameters estimated at a binding bound have no valid robust covariance: their robust standard errors are NA, with a warning, and the other parameters treat them as fixed. A bound binds if the estimate would move past it without the bound; an estimate merely close to a bound has the usual robust standard error. A defined (:=) parameter has an NA robust standard error if it depends on any bounded parameter. Robust covariance also warns when the OpenMx status code is neither 0 nor 1, because the fit may not have converged.

For two-level fits, robust covariance uses each cluster's complete relational-model likelihood score, without a \(G/(G-1)\) factor, as in lavaan's two-level models. Each score needs one OpenMx run that differentiates the cluster's likelihood numerically, which takes several likelihood evaluations per free parameter, so computing time grows with both the number of clusters and the number of parameters. In combined group and two-level models, clusters are nested within groups: each group's clusters are formed from that group's rows only, so a cluster ID used in two groups denotes two different clusters, and a unit spanning groups cannot be represented. sem() warns when an ID appears in more than one group, and robust covariance stops with an error in that case. Cluster IDs generated from summary input are prefixed by the group's position (e.g., "2.5" for cluster 5 in the second group) when they would otherwise repeat. Robust summaries require intervals.type="z"; likelihood-based intervals are not robust.

Examples

Run this code

# \donttest{
## Generate data
set.seed(100)
n <- 100
x <- rnorm(n)
y <- 0.5*x + rnorm(n, mean=0, sd=sqrt(1-0.5^2))
my.df <- data.frame(y=y, x=x)

## A regression model
model <- "y ~ x   # Regress y on x
          y ~ 1   # Intercept of y
          x ~ 1   # Mean of x"
plot(model)

RAM <- lavaan2RAM(model, obs.variables=c("y", "x"))

my.fit <- sem(RAM=RAM, data=my.df)
summary(my.fit)

## A meta-analysis
model <- "f =~ 1*yi
          f ~ mu*1          ## Average effect
          f ~~ tau2*f       ## Heterogeneity variance
          yi ~~ data.vi*yi  ## Known sampling variance"
plot(model)

## Do not standardize the latent variable (f): std.lv=FALSE 
RAM <- lavaan2RAM(model, obs.variables="yi", std.lv=FALSE)

## Use likelihood-based CI
my.fit <- sem(RAM=RAM, data=Hox02, intervals="LB")
summary(my.fit)

## A 2-group regression with a shared slope but group-specific intercepts
x1 <- rnorm(100); y1 <- 2 + 0.5*x1 + rnorm(100)
x2 <- rnorm(100); y2 <- -1 + 0.5*x2 + rnorm(100)
my.df2 <- data.frame(y=c(y1, y2), x=c(x1, x2),
                     g=rep(c("g1", "g2"), each=100))

model <- "y ~ c(b,b)*x + c(a1,a2)*1"
RAM <- lavaan2RAM(model, ngroups=2)
my.fit <- sem(RAM=RAM, data=my.df2, group="g")
summary(my.fit)

## The same 2-group regression, extended with replace.constraints=TRUE:
## group 2's residual variance is constrained to be exactly TWICE group
## 1's, and group 1's own residual variance is reparameterised through
## exp() (guaranteeing positivity). "resid1" never appears as a free
## parameter itself -- lavaanify() would otherwise reject "a0" as
## undeclared, and an ordinary (non-replaced) "==" constraint cannot
## introduce a new free parameter this way; only replace.constraints=
## TRUE can. The constraint chain is resolved across groups, so
## "resid2" ends up expressed directly in terms of "a0" (not "resid1").
model <- "y ~ c(b,b)*x + c(a1,a2)*1
          y ~~ c(resid1,resid2)*y
          resid1 == exp(a0)
          resid2 == 2*resid1"
RAM <- lavaan2RAM(model, ngroups=2)
my.fit <- sem(RAM=RAM, data=my.df2, group="g", replace.constraints=TRUE)
summary(my.fit)

## A two-level (random-intercept) regression model
set.seed(123)
nClusters <- 60; nPerCluster <- 6
clusterID <- rep(seq_len(nClusters), each=nPerCluster)
u <- rep(rnorm(nClusters, 0, 0.7), each=nPerCluster)
x <- rnorm(nClusters*nPerCluster)
y <- 1.5 + 0.6*x + u + rnorm(nClusters*nPerCluster)
my.df3 <- data.frame(clusterID=clusterID, x=x, y=y)

model <- "level: 1
            y ~ b1*x
            y ~~ residW*y
          level: 2
            y ~ 1
            y ~~ residB*y"
RAM <- lavaan2RAM(model)
my.fit <- sem(RAM=RAM, data=my.df3, cluster="clusterID")
summary(my.fit)

## A 2-group CFA: test whether factor loadings are invariant across groups
set.seed(103)
simGroup <- function(n, loadings) {
  f <- rnorm(n)
  Y <- sapply(loadings, function(l) l*f + rnorm(n, sd=0.5))
  colnames(Y) <- paste0("y", seq_along(loadings))
  data.frame(Y)
}
loadings <- c(1, 0.8, 1.3, 0.9)
my.df4 <- rbind(cbind(simGroup(250, loadings), g="g1"),
               cbind(simGroup(250, loadings), g="g2"))

## Metric invariance: loadings constrained equal across groups.
## std.lv=FALSE: the factor's scale is already identified by fixing
## y1's loading at 1 (c(1,1)*y1), so its variance ("f ~~ c(vf1,vf2)*f")
## is left free and group-specific instead of also being fixed at 1 --
## lavaan2RAM()'s default std.lv=TRUE would otherwise silently discard
## that "f ~~ ..." line, fixing the variance at 1 in both groups with
## no error (see lavaan2RAM()'s "std.lv" argument for details).
model.invariant <- "f =~ c(1,1)*y1 + c(l2,l2)*y2 + c(l3,l3)*y3 + c(l4,l4)*y4
                    f ~~ c(vf1,vf2)*f
                    y1 ~ c(m1a,m1b)*1
                    y2 ~ c(m2a,m2b)*1
                    y3 ~ c(m3a,m3b)*1
                    y4 ~ c(m4a,m4b)*1"
fit.invariant <- sem(RAM=lavaan2RAM(model.invariant, ngroups=2, std.lv=FALSE),
                     data=my.df4, group="g")

## Configural model: loadings free in each group
model.free <- "f =~ c(1,1)*y1 + c(l2a,l2b)*y2 + c(l3a,l3b)*y3 + c(l4a,l4b)*y4
               f ~~ c(vf1,vf2)*f
               y1 ~ c(m1a,m1b)*1
               y2 ~ c(m2a,m2b)*1
               y3 ~ c(m3a,m3b)*1
               y4 ~ c(m4a,m4b)*1"
fit.free <- sem(RAM=lavaan2RAM(model.free, ngroups=2, std.lv=FALSE),
                data=my.df4, group="g")

summary(fit.invariant)
anova(fit.free, fit.invariant)   # likelihood-ratio test of metric invariance

## Group difference in the factor variance, as a derived quantity
model.diff <- paste(model.free, "\ndiff_v := vf2 - vf1")
fit.diff <- sem(RAM=lavaan2RAM(model.diff, ngroups=2, std.lv=FALSE),
               data=my.df4, group="g")
summary(fit.diff)   # see "Mxalgebras" in the printed output for diff_v

## A two-level CFA: a factor at the within level and another at the
## between level, with the same three indicators loading on both
set.seed(104)
nClusters <- 100; nPerCluster <- 8; N <- nClusters*nPerCluster
clusterID <- rep(seq_len(nClusters), each=nPerCluster)
fb <- rep(rnorm(nClusters, 0, 1), each=nPerCluster)
fw <- rnorm(N, 0, 1)
ly2 <- 0.8; ly3 <- 1.2
y1 <- fb + fw + rnorm(N, 0, 0.5)
y2 <- ly2*fb + ly2*fw + rnorm(N, 0, 0.5)
y3 <- ly3*fb + ly3*fw + rnorm(N, 0, 0.5)
my.df5 <- data.frame(clusterID=clusterID, y1=y1, y2=y2, y3=y3)

model <- "level: 1
            fw =~ y1 + y2 + y3
          level: 2
            fb =~ y1 + y2 + y3"
RAM <- lavaan2RAM(model)
my.fit <- sem(RAM=RAM, data=my.df5, cluster="clusterID")
summary(my.fit)

## A two-level (multilevel) meta-analysis: studies contributing several
## dependent effect sizes each, separating within- from between-study
## heterogeneity while accounting for each effect size's own known
## sampling variance
set.seed(106)
nStudies <- 60
esPerStudy <- sample(2:4, nStudies, replace=TRUE)
studyID <- rep(seq_len(nStudies), esPerStudy)
N <- length(studyID)
mu <- 0.35; tau2.between <- 0.03; tau2.within <- 0.015
studyEffect <- rep(rnorm(nStudies, mu, sqrt(tau2.between)), esPerStudy)
vi <- runif(N, 0.02, 0.06)
yi <- rnorm(N, studyEffect + rnorm(N, 0, sqrt(tau2.within)), sqrt(vi))
my.df6 <- data.frame(studyID=studyID, yi=yi, vi=vi)

## fw's own variance is the WITHIN-study heterogeneity; yi's own residual
## (after removing fw) is fixed at the KNOWN sampling variance; the
## BETWEEN-study heterogeneity is yi's own variance at level 2
model <- "level: 1
            fw =~ 1*yi
            fw ~~ tauW*fw
            yi ~~ data.vi*yi
          level: 2
            yi ~ mu*1
            yi ~~ tauB*yi"
RAM <- lavaan2RAM(model, std.lv=FALSE)
my.fit <- sem(RAM=RAM, data=my.df6, cluster="studyID")
summary(my.fit)

## A two-level location-scale meta-analysis: replace.constraints=TRUE
## lets the WITHIN-study heterogeneity (tauW, on fw) be a function of an
## effect-size-level moderator xi, while yi's own residual stays fixed
## at its KNOWN sampling variance (data.vi), exactly as in the previous
## example. data.xi is a definition variable, so its per-row value is
## looked up from the data instead of estimated. "tauW" never appears
## as a free parameter itself here -- lavaanify() would otherwise reject
## a0/a1 as undeclared, and an ordinary (non-replaced) "==" constraint
## cannot introduce new free parameters this way; only
## replace.constraints=TRUE can.
set.seed(107)
xi <- rnorm(N)
a0 <- -4; a1 <- 0.8
tauWi <- exp(a0 + a1*xi)
yi2 <- rnorm(N, studyEffect + rnorm(N, 0, sqrt(tauWi)), sqrt(vi))
my.df7 <- data.frame(studyID=studyID, yi=yi2, vi=vi, xi=xi)

model <- "level: 1
            fw =~ 1*yi
            fw ~~ tauW*fw
            yi ~~ data.vi*yi
          level: 2
            yi ~ mu*1
            yi ~~ tauB*yi
          tauW == exp(a0 + a1*data.xi)"
RAM <- lavaan2RAM(model, std.lv=FALSE)
my.fit <- sem(RAM=RAM, data=my.df7, cluster="studyID",
              replace.constraints=TRUE)
summary(my.fit)
# }

Run the code above in your browser using DataLab