2  The lavaan model syntax

2.1 Introduction

A fundamental feature of lavaan is its model syntax, which is used to specify a statistical model. While most often applied to structural equation models (SEMs), the syntax is flexible enough to describe other types of models as well. A typical example is shown below:

model <- '
  f1 =~ y1 + y2 + y3
  f2 =~ y4 + y5 + y6
  f1 ~ f2
'

The model syntax is written as plain text enclosed in single quotes. Double quotes are also supported, but single quotes allow for the use of double quotes within the model syntax, a feature specific to how R handles string literals. For further details, see the help file ?Quotes in R.

The model syntax is often assigned to a variable (in this case, model) for ease of reference. In the example above, the model contains three formulas, each placed on a separate line. Every formula includes an operator, which defines the relationship between the left-hand side (lhs) and the right-hand side (rhs) of the equation. In the first two formulas, the operator =~ specifies a latent variable, whereas in the third formula the operator ~ indicates a regression relationship.

In summary, each formula in the model syntax is composed of three elements:

  1. Left-hand side (lhs): the variable on the left side of the operator.
  2. Operator (op): the symbol that defines the relationship between the lhs and rhs.
  3. Right-hand side (rhs): the variable(s) or expression(s) on the right side of the operator.

2.1.1 Using the + symbol in a formula

It is common, particularly on the right-hand side of a formula, to encounter multiple terms separated by the + operator. Consider, for example, the following specification of a univariate regression with three predictors:

y ~ x1 + x2 + x3

In this expression, the right-hand side contains three terms (x1, x2, and x3), corresponding to the three predictors. Internally, however, the model syntax is expanded into the following equivalent representation:

y ~ x1
y ~ x2
y ~ x3

In this expanded version, each formula contains only a single term on both the left-hand and right-hand sides. This representation is referred to as the flattened model syntax. Conceptually, the flattened version with three formulas is identical to the original single-line specification. Its main advantage, however, is that it typically establishes a one-to-one correspondence between the model’s parameters and the formulas. In this case, each of the three formulas corresponds directly to a regression coefficient.

Flattening the model syntax is one of the first operations performed by lavaan when parsing the input. The function responsible for this task, among others, is lavParseModelString(). The following example demonstrates how a single-line formula is expanded:

lavParseModelString(model_syntax = 'y ~ x1 + x2 + x3',
                    as_data_frame = TRUE)[, c("lhs", "op", "rhs")]
  lhs op rhs
1   y  ~  x1
2   y  ~  x2
3   y  ~  x3

This function produces a structured representation in the form of a table: an initial, incomplete version of what will eventually become the parameter table. In this table, each row corresponds to a parameter in the model. The concept of the parameter table will be examined in greater detail in Chapter 3.

The + symbol can also be used on the left-hand side of a formula, allowing multiple equations with the same operator and identical right-hand side to be grouped together. For instance, the following three regression equations:

y1 ~ x1 + x2
y2 ~ x1 + x2
y3 ~ x1 + x2

can equivalently be expressed in a more compact form as:

y1 + y2 + y3 ~ x1 + x2

As another example, consider this syntax:

y1 + y2 ~~ x1 + x2

This is equivalent to:

y1 ~~ x1 + x2
y2 ~~ x1 + x2

which, in turn, is equivalent to:

y1 ~~ x1
y1 ~~ x2
y2 ~~ x1
y2 ~~ x2

When the terms form a numbered sequence, the ++ operator expands the range between two terms, so that the nine indicators of a factor can be written as:

f =~ x1 ++ x9

This is expanded to f =~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 before the syntax is flattened. The two tokens around ++ must be identical except for the digits (or letters) that are counted up (or down: x5 ++ x1 runs from x5 to x1): item01 ++ item03 produces item01, item02, and item03, and xa ++ xc produces xa, xb, and xc. If several parts differ, they must all change by the same amount (x1y1 ++ x3y3 gives x1y1, x2y2, and x3y3). A modifier attached to both ends is carried along to every generated term: a numeric constant or a label that is identical at both ends applies to every element (a*x1 ++ a*x3 gives all three loadings the label a), while a label that itself forms a series is expanded along with the variable names (b1*y1 ++ b3*y3 gives the labels b1, b2, and b3). The range can be combined with ordinary + terms and with other ranges, and the operator works on the left-hand side of a formula as well:

lavParseModelString(model_syntax = 'y1 ++ y3 ~ x1 ++ x2 + z',
                    as_data_frame = TRUE)[, c("lhs", "op", "rhs")]
  lhs op rhs
1  y1  ~  x1
2  y1  ~  x2
3  y1  ~   z
4  y2  ~  x1
5  y2  ~  x2
6  y2  ~   z
7  y3  ~  x1
8  y3  ~  x2
9  y3  ~   z

If the two tokens cannot be matched (for example x1 ++ x1_3), or if the labels and the variable names run over a different number of steps (a*x1 ++ b*x3), lavaan stops with a parse error that points to the ++ symbol; so does a range with nothing to count (x1 ++ x1). The ++ operator generates terms within one formula. Families of formulas that differ only by a wave number, as in panel models, are generated by indexed names (Section 2.8).

2.1.2 Multiple formulas on the same line

As a general rule, each line in the model syntax may contain only a single formula, meaning that only one operator is permitted per line. The following syntax is therefore invalid, and the parser will return an error (not shown here):

model <- 'y ~ x1 y ~ x2'
lavParseModelString(model)

If multiple formulas are to be specified on the same line (for example, for compactness), they must be separated by a semicolon (;), as in the following example:

y ~ x1; y ~ x2

Conversely, a single formula may span several lines. The rule the parser applies is simple: a formula continues on the next line when the current line ends with an operator (+, -, *, /, ^, ++, a comma, an opening parenthesis, or a lavaan operator such as =~), or when the next line starts with +, ++, *, a closing parenthesis, or a lavaan operator. A semicolon always ends a formula. The (not recommended) layout below is therefore read as a single formula:

f1 
=~
y1 
+ 
y2 
+ 
y3

whereas a line that ends with a name, followed by a line that starts with a name, begins a new formula. The parser never joins two formulas by guessing: when a line cannot be read as a formula, it stops with an error that points to the offending position.

2.1.3 Model syntax is plain text

Model syntax is plain text (commonly referred to as a ‘string’ in programming). Standard R functions can therefore be used to construct or modify it. For example, the model syntax can be divided into separate components and then combined to create the full specification:

mm_f1 <- 'f1 =~ y1 + y2 + y3'
mm_f2 <- 'f2 =~ y4 + y5 + y6'
reg <- 'f1 ~ f2'
# create full model
model <- c(mm_f1, mm_f2, reg)

This method is particularly useful when multiple models must be constructed that share common parts. Each component can be defined separately and then merged as required.

For instance, when specifying a one-factor model with 20 indicators (such as item1 through item20), writing out each term individually on the right-hand side would be both inefficient and error-prone. Instead, the paste() function in R can be employed to generate the terms automatically:

lhs <- 'f1'
op <- '=~'
rhs <- paste("item", 1:20, collapse = " + ", sep = "")
model <- c(lhs, op, rhs)

In this example, the object model is technically not a single string but a character vector with multiple elements. However, this poses no problem, as the lavaan syntax parser will regard every element of the character vector as a new line of syntax.

2.1.4 Spaces, comments and readable syntax

Model syntax often spans multiple lines, particularly in the case of complex models. To improve readability, it is considered good practice to insert spaces around operators and the + symbol. For example, the following specification:

y1~1*x1+b*x2+c*x3+d*x4

is technically valid but difficult to read. By adding spaces around the operators, the syntax becomes clearer:

y1 ~ 1*x1 + b*x2 + c*x3 + d*x4

It is advisable, however, not to add spaces around the * symbol. In this context, * is not a multiplication operator but instead denotes modifiers, and therefore should remain directly attached to the terms it modifies. Modifiers will be discussed in greater detail in Section 2.3.

When dealing with lengthy lines of syntax, it is acceptable to divide them across multiple lines to further enhance readability. For instance, a factor with many indicators may be specified as follows:

f =~ item1 + item2 + item3 +
     item4 + item5 + item6 +
     item7 + item8 + item9

Including comments in the model syntax is strongly recommended, as they clarify the purpose of each part of the specification and facilitate understanding for others who may need to read or modify the syntax. The parser ignores spaces at the beginning of a line, as well as blank or empty lines, which provides considerable flexibility in formatting the syntax for clarity. The following (somewhat artificial) example illustrates this:

model <- '

# first, the measurement part of the model is specified;
# it consists of two (correlated) factors, f1 and f2, each 
# one measured by three indicators

  # the two latent variables
  f1 =~ y1 + y2 + y3
  f2 =~ y4 + y5 + y6
  
  # correlated residuals
  y2 ~~ y3
  y5 ~~ y6
  
# next, the structural part of the model is specified;
# it simply contains a single regression formula, but
# to make this example slightly more interesting, we
# will fix the residual variance of the dependent variable
# to a constant

  # regression
  f1 ~ f2

  # fixed residual variance
  f1 ~~ 0.9*f1 # the residual variance is fixed to 0.9
               # no idea why, but it allows for more comments.

# as is obvious from the above, comments start with a hash 
# character (#) or an exclamation mark (!)
! so this is also a comment
# and this concludes the example.
'

Both the # and the ! characters can be used to indicate comments. The # character is the standard comment character in R and is therefore recommended. The ! character was included in lavaan because it is often used for comments in other software packages. As the example demonstrates, all text following a comment character is ignored by the parser.

Variable names normally consist of letters, digits, dots, and underscores. A name that contains spaces or other special characters must be quoted, with single or double quotes: "my var" =~ x1 + 'x 2'. Two names separated only by spaces (f =~ x1 x2) are an error, and the message asks for an operator between the two terms, or for quotes around the name. Syntax that has passed through a word processor or a web page may contain characters that look like an operator but are different characters: full-width forms of + or =, the small tilde or the tilde operator in place of ~, the minus sign or the en dash in place of -, curly quotes, and no-break spaces. The parser reads these as the corresponding ASCII character, so that copied syntax works as intended; inside quoted names they are left as they are.

2.2 The three main operators

Each formula must include an operator. The three most commonly used operators in lavaan are as follows:

  1. the latent variable operator, =~, which is used to define latent variables.
  2. the regression operator, ~, which is used to define regressions.
  3. the (co)variance operator, ~~, which is used to specify variances or covariances.

These three operators are discussed in greater detail below.

2.2.1 The latent variable operator: =~

The most central operator in lavaan is the latent variable operator =~, which consists of an equal sign and a tilde. There should be no space between these two symbols. A typical example is the following two-factor model:

f1 =~ y1 + y2 + y3
f2 =~ y4 + y5 + y6

In this syntax, the left-hand side of the formula specifies the name of the latent variable, which is defined by the indicators listed on the right-hand side of the operator. Although the indicators are usually observed variables, they can also be latent variables themselves, as illustrated in a higher-order factor model:

# first order factors
f1 =~ y1 + y2 + y3
f2 =~ y4 + y5 + y6
f3 =~ y7 + y8 + y9
# second order factor
g =~ f1 + f2 + f3

The names of latent variables, such as f1 and f2, can be chosen freely. However, it is essential that latent variable names do not overlap with the names of observed variables in the dataset, even if those observed variables are not explicitly included in the model. Unique names should therefore always be used to avoid ambiguity. In addition, names must begin with a letter and should not contain spaces. Although the current parser permits spaces if the latent variable name is enclosed in double quotes (older parsers did not), it remains advisable to avoid this practice:

"f 1" =~ y1 + y2 + y3

This example also illustrates why it is preferable to enclose lavaan syntax in single quotes rather than double quotes.

Phantom latent variables are latent variables that are not measured but are used for specific purposes, such as defining constraints or enforcing a particular parameterization (Rindskopf, 1984). In lavaan, a phantom latent variable can be defined using the following syntax:

phantom_f =~ 0

The reason why the latent variable operator is written as =~ in lavaan traces back to the early versions of the package, which predated its public release. At that time, the model syntax was not a string, but rather a different format. lavaan originally grew out of a package called cfa2000, which was never publicly released. As the name suggests, cfa2000 was designed specifically for confirmatory factor analysis (CFA). To specify and fit a three-factor CFA in cfa2000, the model was described using a named list, as shown in the example below:

# specify 3-factor CFA model
measurement.model <- 
    list( visual  = c("x1","x2","x3"),
          textual = c("x4","x5","x6"),
          speed   = c("x7","x8","x9") )
# fit the model
fit <- cfa(measurement.model = measurement.model, 
           data = HolzingerSwineford1939)

Here, the names of the list elements corresponded to the names of the latent variables, and the list elements themselves specified the factor indicators for each respective factor. While this approach worked, it was cumbersome, especially with the use of parentheses, commas, and double quotes, making the model specification somewhat complex.

A later version of cfa2000 simplified the syntax by allowing the model to be specified in a way that made use of standard R syntax. The latent variables were now assigned to R formulas using the = assignment operator, and each formula started with the tilde (~) symbol, which is used in R to denote a relationship between variables. This allowed the model to be written as:

# old syntax, do not use
visual  =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed   =~ x7 + x8 + x9

fit <- cfa(measurement.model = list(visual, textual, speed),
           data = HolzingerSwineford1939)

This was a significant step forward in simplifying the syntax and making it more intuitive. However, this approach had limitations, such as not supporting modifiers like labels and fixed values in the formulas. Eventually, the model specification format was changed again, this time to use strings (or vectors of strings), enabling greater flexibility. Despite this change, the =~ operator was retained due to its practicality and consistency with the original intent of describing the relationship between latent variables and their indicators in a clear, readable format.

2.2.2 The regression operator: ~

In R, when the lm() function is used to fit a regression model, the syntax typically looks like this:

y ~ x1 + x2 + x3

In this example, the left-hand side of the formula (y) represents the dependent variable, while the right-hand side (x1 + x2 + x3) lists the predictors, separated by the + symbol. lavaan model syntax allows for similar expressions, but there are some key differences. For instance, in lavaan, the * symbol cannot be used to specify interactions as it does in R’s formula syntax. Instead, in lavaan syntax, the * symbol is reserved for modifiers (e.g., labels and fixed values), which will be discussed in Section 2.3. Interactions are written with the colon (:) instead, just as in R:

y ~ x1 + x2 + x1:x2

When both variables in a product term are observed, lavaan constructs the product variable internally and treats it as an additional predictor. When at least one of them is latent, however, the lavaan()/sem()/cfa() functions reject the model with an informative error message: latent interactions require dedicated methods, which lavaan provides through the sam() function (see the chapter on the structural-after-measurement approach, in particular Section 18.10) and which is also available in the modsem package (Section 4.9).

In other respects, the lavaan syntax is more flexible. For example, a multivariate regression model can be written as a single formula:

y1 + y2 + y3 ~ x1 + x2 + x3

This makes it easy to fit models with multiple dependent variables simultaneously. In fact, a single model may contain multiple regressions, resulting in a system of equations. For instance:

y1 ~ x1 + x2 + x3
y2 ~ y1 + x1
f1 + f2 ~ y1 + y2
w ~ f1 + f2

This type of model is often referred to as path analysis when all variables are observed. In such models, variables that appear on the left-hand side of one formula can also appear on the right-hand side of others, making them both dependent and independent in different equations. These are known as mediators. However, the same variable cannot appear on both sides of a regression formula in the same equation. If this happens, the syntax parser will flag an error.

lavaan’s syntax is also designed to handle latent variables. If any variables are latent, the model syntax should use the =~ operator to define them.

The right-hand side of a regression formula may contain the number 1, as in:

y ~ 1 + x1 + x2 + x3

Here, the 1 represents the intercept in the regression formula, which is the value of the dependent variable (y) when all the predictors are equal to zero. The intercept is treated in the same way as any other predictor in the equation: it can be given a label, and its value can be fixed or free, depending on the model.

If a model syntax specifies no predictors for a variable, such as:

y ~ 1

then the 1 represents the mean of the variable y.

2.2.3 The (co)variance operator: ~~

The third main operator in lavaan model syntax is the (co)variance operator, ~~. This operator consists of two tilde symbols (~~), with no space between them. It is used to define covariances or variances in the model. Two examples:

y1 ~~ y2
f ~~ f

In the first formula, y1 ~~ y2 specifies the covariance between the variables y1 and y2. In the second formula, f ~~ f represents the variance of the variable f, since both sides refer to the same variable.

It is important to note that a covariance in lavaan syntax, such as:

y1 ~~ y2

is not the same as:

y1 ~ y2
y2 ~ y1

While both formulas involve the variables y1 and y2, the latter involves two regression parameters (y1 ~ y2 and y2 ~ y1), each representing a distinct regression equation. In contrast, the former syntax only defines a single covariance parameter, which represents the relationship between y1 and y2.

In terms of variable types, the variables involved in a covariance expression can be either observed or latent. In most cases, both variables will share the same status, meaning they are either both observed or both latent. However, there are rare cases where one variable may be latent while the other is observed. Although this may be unusual conceptually or statistically, it is valid syntax.

2.2.4 Other operators

In addition to the core operators discussed earlier, lavaan includes several other operators that are used in specific contexts. These operators are explained in greater detail where they are first needed. A brief overview of their meanings follows:

  • | operator: Defines thresholds for binary or ordinal variables. For example, for an ordinal variable y1 with 4 ordered categories, three thresholds are specified: y1 | t1 + t2 + t3. The threshold names (t1, t2, and t3) are fixed and must appear in the correct order (i.e., t1 before t2).

  • ~*~ operator: Used to define a scaling parameter. The name of the variable on the left-hand side must match the name on the right-hand side (although this is currently not enforced by the parser). This operator is often used when the variance of a variable is constrained to a constant (usually unity) per default, but the constraint must be relaxed (for example, when different variances are allowed in different groups).

  • <~ operator: Defines composites, which are constructs represented as a weighted sum of their indicators.

  • |~ operator: Specifies the instrumental variables to be used for a particular equation when the instrumental-variables estimator is requested (estimator = "IV"). The left-hand side is the dependent variable of the equation, and the right-hand side lists the instruments. By default, lavaan determines the (model-implied) instruments automatically; this operator overrides that choice.

  • := operator: Used to create or define new parameters that are typically functions of existing model parameters. These new parameters are defined by mathematical expressions.

  • :~ operator: Used to define a data-defined (or moderated) parameter: an existing, labeled parameter is redefined as a function of observed variables (each wrapped in data()) and of new component parameters, as in b :~ b0 + b1 * data(z). Such a model requires a casewise likelihood, and is estimated by an external backend; see the implementation notes at the end of this chapter (Section 2.9).

  • == operator: Specifies equality constraints for model parameters, which can be either linear or nonlinear.

  • < or > operator: Used to specify inequality constraints, which can also be linear or nonlinear.

  • % operator: Used to specify group weights on the log scale. This is only applicable in multiple-group settings where the group size is treated as a random variable.

  • : operator: Defines separate blocks of model parameters. It is particularly useful in multiple-group or multilevel models, allowing different sets of parameters to be specified independently for each group or level.

For later reference, the table below contains all the operators that are currently used in lavaan syntax:

Overview of the operators used in lavaan model syntax.
Operator Formula type Mnemonic Group
=~ latent variable definition is measured by relational
~ regression is regressed on relational
~~ (residual) (co)variance is correlated with relational
<~ composite variable definition is composed of relational
|~ instrumental variables is instrumented by relational
| threshold is cut off at relational
~*~ scaling factor is scaled by relational
% (log) group size has group size relational
== equality constraint is equal to constraint
< inequality constraint is smaller than constraint
> inequality constraint is larger than constraint
:= new parameter definition is defined as constraint
:~ data-defined parameter is moderated by constraint
: block identifier syntax for block blockdef

The ‘relational’ operators define model parameters. The ‘constraint’ operators define constraints for those parameters, or define new parameters, either as a function of other parameters (:=) or as a function of the data (:~). The ‘blockdef’ operator organizes the parameters in blocks.

This table, together with the modifier table later in this chapter, is in effect the vocabulary of the lavaan model language: the complete set of operators that any program claiming to read lavaan syntax must understand. The lavaan syntax has become a de facto standard well beyond the package itself: it is read by GUI front-ends and re-implemented by SEM software in other languages.

2.3 Modifiers

In model formulas, additional information can be provided for each term on the right-hand side of the operator. For example, consider the following syntax:

y ~ b1*x1 + start(0.5)*x2 + 1.2*x3 + x4

In this case, the first three terms are modified using the modifier symbol *, while no modifier is applied to the last term (x4). The effect of these modifiers is to adjust certain aspects of the corresponding parameters.

  • The first modifier (b1*) assigns a user-defined label (“b1”) to the regression coefficient of x1.

  • The second modifier (start(0.5)*) sets a user-specified starting value of 0.5 for the regression coefficient of x2.

  • The third modifier (1.2*) fixes the regression coefficient of x3 to the value 1.2.

These are the three most commonly used modifiers in lavaan model syntax, and they will be discussed in more detail below.

2.3.1 Giving labels to parameters

It is often convenient to assign user-specified names to particular parameters. These names are called (parameter) labels. Labels should be short (for example, a2 or beta2) and must start with a letter. Spaces should be avoided.

Certain names cannot be used as labels because they are reserved words or special constants in R such as NA, if, for, Inf, and NaN (see ?reserved). They should be avoided inside lavaan model syntax.

A typical example of labeled parameters in a regression model looks like this:

y1 ~ b0*1 + b1*x1 + b2*x2 + b3*x3
y1 ~~ residual_error*y1

Here, the first formula specifies the regression model and assigns labels (b0, b1, b2, b3) to the regression coefficients, including the intercept. The second formula specifies the residual variance of the dependent variable and assigns it the label residual_error.

When all labels are unique (as in this example), they have no effect on the model. They are shown next to the corresponding parameters in the output. As an illustration, the model is fitted to a built-in dataset (Demo.twolevel), and a portion of the output is shown:

model <- '
  y1 ~ b0*1 + b1*x1 + b2*x2 + b3*x3
  y1 ~~ residual_error*y1
'
fit <- sem(model, data = Demo.twolevel)
parameterEstimates(fit, ci = FALSE, output = "text")
Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  y1 ~                                                
    x1        (b1)    0.500    0.032   15.453    0.000
    x2        (b2)    0.383    0.032   12.029    0.000
    x3        (b3)    0.159    0.031    5.085    0.000

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y1        (b0)    0.026    0.032    0.822    0.411

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y1      (rsd_)    2.567    0.073   35.355    0.000

In the output, long labels such as residual_error are automatically abbreviated. For this reason, short labels are generally more convenient. Other extractor functions (such as coef()) may show the full label without abbreviation:

coef(fit)
            b0             b1             b2             b3 residual_error 
         0.026          0.500          0.383          0.159          2.567 

Labels are especially helpful in large models: a labeled parameter of particular interest is easy to locate in the potentially long output.

So far, labels have been used primarily for convenience. However, labels also become essential when defining new parameters or imposing (in)equality constraints, as will be demonstrated later.

2.3.2 Fixing parameter values

Another common use of modifiers is to fix the value of a model parameter to a pre-specified number. This is done by placing a number (or an expression that returns a number) in front of the modifier symbol *.

For example, in a growth curve model, a random intercept and a random slope can be defined as follows:

int =~ 1*y1 + 1*y2 + 1*y3 + 1*y4
slope =~ 0*y1 + 1*y2 + 2*y3 + 3*y4

Another example is a two-factor model where the two factors are forced to be uncorrelated:

f1 =~ y1 + y2 + y3
f2 =~ y4 + y5 + y6
f1 ~~ 0*f2

Instead of specifying a constant value directly, it is also possible to use an expression that evaluates to a number. For instance:

y ~ x1 + log(3)*x2

Here, log(3) will be evaluated first, and the resulting numerical value will be used to fix the regression coefficient for x2. (How such expressions are evaluated, and which expressions remain valid outside R, is discussed in the implementation notes at the end of this chapter, Section 2.9.) To avoid ambiguity, especially with more complex expressions, parentheses can be used:

y ~ x1 + (1 + log(3))*x2 + (-2.3)*x3

Although it may seem unusual, the value of the intercept can also be fixed in a regression formula:

y1 ~ 3*1 + 0.5*x1 + x2
y2 ~ 0*1

In the first model formula, the value of the intercept (of y1) is fixed to the number 3. In the second formula, the mean of the variable y2 is fixed to zero. Because the latter is often used, there is a shortcut. An equivalent specification for the second formula is as follows:

y2 ~ 0

This is a shorthand notation that fixes the mean of y2 to zero. A bare number on the right-hand side of ~ must be 0 or 1 (any other value is a parse error), and on the right-hand side of =~ it must be 0, the phantom-variable notation introduced with the latent variable operator.

Finally, it is also possible to use the missing value symbol NA instead of a constant. For example:

model <- '
  f =~ NA*y1 + y2 + y3
  f ~~ 1*f
'
fit <- sem(model, data = Demo.twolevel)

In this case, because the variance of the latent variable f is already fixed to 1, there is no need to fix the first factor loading to 1. Using NA* makes this explicit: it indicates that the corresponding parameter should be treated as ‘unknown’, that is, it should remain free to be estimated.

2.3.3 Starting values

For most standard models, lavaan automatically generates starting values for all free parameters. However, users can manually provide custom starting values for one or more parameters. For example:

y ~ start(0.5)*x1 + start(-2.3)*x2 + x3

In this syntax:

  • The starting value for the regression coefficient of x1 is set to 0.5.

  • The starting value for the regression coefficient of x2 is set to -2.3.

  • For x3, no custom starting value is specified, so the default starting value will be used.

User-specified starting values always override the default ones generated by lavaan.

When setting custom starting values, it is important to ensure that the values are feasible. Consider the following example:

y1 ~~ 1*y1
y2 ~~ 1*y2
y1 ~~ start(3.5)*y2

In this case, the variances of y1 and y2 are fixed to 1, meaning the variables are standardized. Consequently, the covariance between y1 and y2 should lie between -1 and +1 (as it is on the correlation scale). Setting a starting value of 3.5 is therefore invalid. Although lavaan often detects such mistakes and issues a warning, it remains the user’s responsibility to provide valid and meaningful starting values.

Rather than applying the start()* modifier explicitly, initial values can be defined more concisely using the ? shorthand:

y ~ 0.5?x1 + (-2.3)?x2 + x3

This is purely a notational convenience; internally, it is translated to:

y ~ start(0.5)*x1 + start(-2.3)*x2 + x3

2.3.4 Deprecated modifiers

There are three modifiers that are still supported for backward compatibility, but they should no longer be used in new model syntax.

The fixed()* modifier was the original notation for fixing the value of a parameter. For example:

y ~ x1 + fixed(0.5)*x2 + x3

fixes the regression coefficient of x2 to 0.5. The preferred notation is:

y ~ x1 + 0.5*x2 + x3

The label()* modifier was used to assign a label to a parameter. For example:

y ~ label("b1")*x1 + label("b2")*x2 + label("b3")*x3

The current, more concise notation is:

y ~ b1*x1 + b2*x2 + b3*x3

Finally, the equal()* modifier was used to specify simple equality constraints. It required at least one ‘target’ parameter to be labeled, and then constrained other parameters to be equal to it. For example:

y ~ label("b")*x1 + equal("b")*x2 + equal("b")*x3

The same constraint is now written as:

y ~ b*x1 + b*x2 + b*x3

2.3.5 Other modifiers

The lower()* and upper()* modifiers are used to set lower and upper bounds on model parameters. For example:

y ~ x1 + lower(-2)*x2 + upper(5)*x3

In this example, the regression coefficient for x2 is constrained to be no smaller than -2 (lower bound), while the regression coefficient for x3 is constrained to be no larger than 5 (upper bound).

The rv()* modifier flags a regression coefficient to be treated as random, and is used in multilevel modeling for defining random slopes. The (quoted) argument of rv() is the name of the random slope, which becomes a latent variable at the between level. For example:

level: 1
  fw =~ y1 + y2 + y3
  fw ~ rv("s1")*x1
level: 2
  fb =~ y1 + y2 + y3
  s1 ~ w

In the sem(), cfa() and growth() functions, a random slope is by default correlated with the other random effects of the between level (here, the residual covariance between s1 and fb is a free parameter); see Section 16.13.2.

For later reference, the table below contains all the modifiers that are currently supported in lavaan syntax. All modifiers should be used on the right-hand side of a relational operator. The only exception is the last one (efa()*), which should only be used on the left-hand side of the =~ operator.

Overview of modifiers in the lavaan model syntax.
Modifier Purpose
start(123)* provide starting value 123
123? provide starting value 123
123* fix parameter (here to 123)
fixed(123)* fix parameter (here to 123) (deprecated)
NA* free parameter
abc* label parameter (here to abc)
label("abc")* label parameter (here to abc) (deprecated)
lower(0)* enforce lower bound (here 0)
upper(10)* enforce upper bound (here 10)
equal("abc")* make equal to target parameter (here abc) (deprecated)
rv("s1")* flag regression coefficient as a random slope (here s1)
efa("set1")* assign factor to exploratory block set1 (lhs only)

2.3.6 Using multiple modifiers simultaneously

Sometimes, it is necessary to apply multiple modifiers to a single model parameter. For example, it may be necessary to assign both a label and a fixed value to a parameter.

In older versions of lavaan, the only way to do this was to repeat the term multiple times within the same formula, each time with a different modifier. For example:

y ~ x1 + b2*x2 + 0.3*x2

In this syntax:

  • The first occurrence (b2*) assigns the label b2 to the regression coefficient for x2.

  • The second occurrence (0.3*) fixes the coefficient to the value 0.3.

The current syntax parser allows specifying multiple modifiers at once for the same term, using multiple * symbols:

y ~ x1 + b2*0.3*x2

Here, the label b2 is assigned, and the coefficient is simultaneously fixed at 0.3.

In short, multiple uses of the * symbol are now supported for a single term, simplifying the model syntax.

2.3.7 Left-hand side modifiers

In general, modifiers in lavaan syntax only appear on the right-hand side of an operator. The only exception is the efa()* modifier, which can be used on the left-hand side of the latent variable operator =~. This modifier is specifically intended for exploratory structural equation modeling (ESEM).

In ESEM, the model can include both confirmatory and exploratory components. Confirmatory factors have a fixed loading pattern, reflecting prior hypotheses about which indicators measure which latent constructs. In contrast, exploratory factors do not have a pre-specified loading pattern; their loadings are freely estimated and then subjected to a rotation procedure to achieve a more interpretable factor structure. By default, lavaan assumes that all factors are confirmatory. To distinguish exploratory factors, the efa()* modifier should be used on the left-hand side. For example:

# exploratory set1
efa("set1")*f1 +
efa("set1")*f2 =~ y1 + y2 + y3 + y4 + y5 + y6
# exploratory set2
efa("set2")*f3 +
efa("set2")*f4 =~ y7 + y8 + y9 + y10 + y11 + y12
# confirmatory set
f5 =~ y13 + y14 + y15
f6 =~ y16 + y17 + y18

In this setup, f1 and f2 are exploratory factors grouped in the set "set1", while f3 and f4 are exploratory factors in "set2". Factors f5 and f6 are confirmatory and modeled using the standard confirmatory approach. The factors within each exploratory set are rotated together (f1 and f2 share one rotation, and f3 and f4 share another), whereas no rotation is applied to the confirmatory factors f5 and f6.

2.4 User-defined parameters

When fitting a statistical model, the output typically reports the estimated values of the model parameters. However, it is often useful to compute additional quantities that can be expressed as functions of these parameters, even when the functions are complex. This can be achieved with the := operator, which defines a new variable as a function of the existing model parameters.

To make use of this functionality, model parameters must first be assigned labels. These labels can then be referenced as placeholders for the corresponding parameter estimates. For example, consider a regression model with three predictors:

y1 ~ b1*x1 + b2*x2 + b3*x3

If the goal is to obtain the sum of the three regression coefficients, a new parameter (e.g., sum_of_beta) can be defined as follows:

sum_of_beta := b1 + b2 + b3

To illustrate how this works in practice, the model can be fitted using the demo dataset, and the output examined:

model <- '
  y1 ~ b1*x1 + b2*x2 + b3*x3
  sum_of_beta := b1 + b2 + b3
'
fit <- sem(model, data = Demo.twolevel)
parameterEstimates(fit, ci = FALSE, output = "text")
Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  y1 ~                                                
    x1        (b1)    0.500    0.032   15.453    0.000
    x2        (b2)    0.383    0.032   12.029    0.000
    x3        (b3)    0.159    0.031    5.085    0.000

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y1                2.567    0.073   35.355    0.000

Defined Parameters:
                   Estimate  Std.Err  z-value  P(>|z|)
    sum_of_beta       1.042    0.055   18.912    0.000

In the resulting output, a section titled Defined Parameters appears at the bottom. This section lists all user-defined quantities. It can be confirmed that the reported value of sum_of_beta matches the sum of the three regression coefficients. While a simple sum may not appear particularly useful, the := operator becomes more useful when defining more complex functions of the parameters. For instance, one might compute the following somewhat unusual quantity:

complex_f_of_beta := (1 + exp(b1^2) + b2^3) - sqrt(b3)

Any valid R expression can be placed on the right-hand side of a := formula, regardless of its complexity (although the portability caveat of the implementation notes, Section 2.9, applies here as well). Moreover, once a new parameter has been defined, it can be referenced in the definition of subsequent parameters. For example, if in addition to the sum of the coefficients we also wish to compute the square of that sum, the following can be written:

sum_of_beta := b1 + b2 + b3
squared_sum_of_beta := sum_of_beta^2

This approach allows complex, layered calculations to be integrated directly into the model syntax, ensuring that the specification remains transparent, explicit, and reproducible.

2.4.1 A simple mediation analysis

The use of labels and defined parameters facilitates mediation analysis, a common statistical procedure. In its simplest form, mediation analysis involves three variables: an outcome variable y, an exposure variable x, and a mediator variable m. The corresponding model can be specified as:

y ~ m + x
m ~ x

In addition to estimating the direct relationships, mediation analysis typically focuses on the indirect effect of x on y (mediated through m) and the total effect of x on y. These quantities can be defined by labeling the regression coefficients and applying the := operator:

model <- '
  y ~ b*m + c*x
  m ~ a*x
  # defined parameters
  indirect := a*b
  total := (a*b) + c
'

The output will include the estimated values for both the indirect and the total effect.

For a single mediator, writing out the effects with := is manageable. In larger structural models, with several mediators, chains of mediators, or multiple outcomes, writing every indirect and total effect by hand becomes tedious and error-prone. In that case, the := lines can be omitted altogether: the function lavEffects() computes all total, indirect, and direct effects automatically from a fitted object, including standard errors and (Monte Carlo or bootstrap) confidence intervals; see Section 8.4.15.

2.5 Equality and inequality constraints

In some situations, it is desirable to impose constraints on model parameters, either to incorporate prior knowledge or to ensure that the model satisfies specific requirements. Two primary types of constraints can be applied: equality constraints and inequality constraints.

2.5.1 Simple equality constraints

When the same label appears more than once in the model syntax, it means the values of those parameters are constrained to be equal. The general rule is: the same label implies the same value.

For instance, in a regression model, the three regression coefficients can be constrained to be equal by assigning them the same label. An example is shown below:

model <- '
  y1 ~ b*x1 + b*x2 + b*x3
'
fit <- sem(model, data = Demo.twolevel)
parameterEstimates(fit, ci = FALSE, output = "text")
Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  y1 ~                                                
    x1         (b)    0.344    0.019   18.493    0.000
    x2         (b)    0.344    0.019   18.493    0.000
    x3         (b)    0.344    0.019   18.493    0.000

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y1                2.628    0.074   35.355    0.000

This rule applies to any type of parameter. Even when the parameters are of different types, like factor loadings and covariance parameters, they can still be constrained to be equal by giving them the same label:

model <- '
  f1 =~ y1 + a*y2 + y3
  f2 =~ y4 + y5 + y6
  f1 ~~ a*f2
'

In both cases, the use of the same label ensures that the specified parameters are constrained to have the same estimated value.

2.5.2 General equality constraints

In some situations, more complex equality constraints are required. For instance, it may be desirable to estimate factor loadings such that their mean equals one. The == operator can be used to specify that the left-hand side of an equation is equal to the right-hand side, enabling the imposition of precise equality relationships among model parameters.

For example, suppose a regression model is estimated with the additional constraint that the sum of the regression coefficients equals one. This can be specified as follows:

model <- '
  y1 ~ b1*x1 + b2*x2 + b3*x3
  # linear equality constraint
  b1 + b2 + b3 == 1
'
fit <- sem(model, data = Demo.twolevel)
parameterEstimates(fit, ci = FALSE, remove_eq = FALSE, output = "text")
Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  y1 ~                                                
    x1        (b1)    0.485    0.026   18.563    0.000
    x2        (b2)    0.369    0.026   14.142    0.000
    x3        (b3)    0.146    0.026    5.646    0.000

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y1                2.568    0.073   35.355    0.000

Constraints:
                                               |Slack|
    b1+b2+b3 - (1)                               0.000

The output will show that the estimated regression coefficients sum exactly to one. The slack of a constraint represents the difference between its left-hand side and right-hand side. In this example, the slack is zero, indicating that the equality constraint has been fully satisfied.

Another example illustrates the use of ‘effect coding’ for factor loadings, where the loadings are estimated such that their mean equals one. This can be implemented as follows:

model <- '
  f =~ a*y1 + b*y2 + c*y3 + d*y4
  # linear equality constraint
  (a + b + c + d)/4 == 1
'
fit <- sem(model, data = Demo.twolevel, auto_fix_first = FALSE)

This constraint sets the metric for the latent variable, eliminating the need to fix the first factor loading to one. This explains the inclusion of the argument auto_fix_first = FALSE.

Equality constraints can also be applied to defined parameters. For example, one could first define a parameter for the mean of the factor loadings and then impose an equality constraint to enforce that the mean equals one:

# defined parameter
mean_of_loadings := (a + b + c + d)/4
# equality constraint
mean_of_loadings == 1

The constraints in these examples are linear equality constraints, expressed as weighted sums of the involved parameters. Linear equality constraints are computationally efficient, making them relatively straightforward and fast to handle during model optimization.

More complex constraints, including nonlinear equality constraints, can also be specified. For example:

y1 ~ b1*x1 + b2*x2 + b3*x3
# nonlinear equality constraint
b1 == b2^2 + exp(b3)

In this case, the regression coefficient b1 is constrained to follow a nonlinear function of b2 and b3. Similar to linear constraints, any valid R expression can be used on either side of the == operator (with, once more, the portability caveat of the implementation notes, Section 2.9).

2.5.3 Inequality constraints

The == operator allows the specification of equality constraints, and similarly, the < and > operators can be used to impose inequality constraints within a model (<= and >= are accepted as synonyms; a single = is not an operator of the lavaan syntax, and the parser asks whether == was intended). These constraints enable parameter estimates to adhere to theoretical expectations or substantive assumptions.

Consider a regression model with three predictors, with regression coefficients labeled b1, b2, and b3. To enforce an ordering where b1 is no larger than b2, and b2 is no larger than b3, the syntax is:

model <- '
  y1 ~ b1*x1 + b2*x2 + b3*x3
  # linear inequality constraint
  b1 < b2
  b2 < b3
'
fit <- sem(model, data = Demo.twolevel)
parameterEstimates(fit, ci = FALSE, remove_ineq = FALSE, output = "text")
Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  y1 ~                                                
    x1        (b1)    0.344    0.019   18.493    0.000
    x2        (b2)    0.344    0.019   18.493    0.000
    x3        (b3)    0.344    0.019   18.493    0.000

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y1                2.628    0.074   35.355    0.000

Constraints:
                                               |Slack|
    b2 - (b1)                                    0.000
    b3 - (b2)                                    0.000

This approach exemplifies order-constrained regression. Notably, the solution that best satisfies these constraints may result in all three regression coefficients being equal. In lavaan, < and > are interpreted inclusively, effectively as <= and >=, allowing equality when it leads to an improved model fit.

The output includes slack values, which quantify the difference between the left- and right-hand sides of each constraint. In this example, both slack values are zero, indicating that the constraints are active and the estimates lie exactly on the boundary of the permitted region.

If the inequalities were reversed:

b1 > b2
b2 > b3

the estimation would recover the original unconstrained solution. In this case, the slack values would be positive, indicating that the constraints are inactive; they do not affect the estimation because the data already satisfy them naturally.

As with equality constraints, inequality constraints can involve complex, nonlinear functions. For instance:

b1 < b2^2 + exp(b3)

This flexibility has a drawback: specifying inequality or nonlinear equality constraints triggers constrained optimization, which is more demanding and can slow down estimation or occasionally cause instability. Providing reasonable starting values for parameters involved in these constraints is recommended to aid the optimizer.

2.5.4 Lower and upper bounds for model parameters

Simple inequality constraints provide a way to impose lower or upper bounds on parameters without introducing complex relationships. For example, one may require that a regression coefficient b1 is nonnegative (b1 > 0), while another coefficient b2 remains below 10 (b2 < 10). This can be expressed explicitly as:

y1 ~ b1*x1 + b2*x2 + b3*x3
# inequality constraints
b1 > 0
b2 < 10

For such ‘simple’ constraints, lavaan provides a more efficient approach: lower and upper limits can be applied directly within the model syntax using lower() and upper() modifiers:

y1 ~ lower(0)*x1 + upper(10)*x2 + x3

Parameter labels can also be included if desired:

y1 ~ lower(0)*b1*x1 + upper(10)*b2*x2 + b3*x3

These bounds are not limited to regression coefficients. For instance, if two variables are standardized with unit variance, any covariance between them must fall between -1 and +1. This natural constraint can be enforced as follows:

# standardized variables
y1 ~~ 1*y1
y2 ~~ 1*y2
# lower/upper bound for the covariance
y1 ~~ lower(-1)*upper(+1)*y2

Such simple bounds are passed as box constraints to the optimizer, which handles them directly (see Section 7.1): estimation with such limits is almost as fast and stable as fitting an unconstrained model. To avoid invoking fully constrained estimation, lavaan evaluates all inequality constraints (those explicitly specified with < or >), and automatically converts simple constraints into corresponding lower and upper bounds internally.

2.6 Syntax for multiple groups

In multiple-group analyses, the model syntax often remains unchanged, since the same model is typically estimated across all groups. (The less common scenario, in which each group has a distinct model, is discussed in Section 2.7.1.)

A particularly important application of multiple-group modeling is measurement invariance testing. This procedure assesses whether the relationship between latent variables and their indicators (and, by extension, the interpretation of those latent variables) remains consistent across groups. For continuous indicators, a standard three-step sequence is typically used:

  1. Configural invariance: The same factor structure is applied across all groups.

  2. Weak invariance: Factor loadings are constrained to be equal across groups.

  3. Strong invariance: Both factor loadings and intercepts are constrained to be equal across groups.

The Holzinger & Swineford dataset, which includes two groups representing two schools, can be used to illustrate this process. The first step involves fitting the configural model:

model <- '
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
'
fit1 <- sem(model, data = HolzingerSwineford1939, group = "school")

To fit the weak and strong invariance models, the same model syntax is reused, with the group_equal= argument specifying which parameters should be constrained across groups:

fit2 <- sem(model, data = HolzingerSwineford1939, group = "school",
           group_equal = "loadings")
fit3 <- sem(model, data = HolzingerSwineford1939, group = "school",
           group_equal = c("loadings", "intercepts"))

Likelihood ratio tests can then be used to compare the three models:

lavTestLRT(fit1, fit2, fit3)
Chi-Squared Difference Test

     Df    AIC    BIC  Chisq Chisq diff    RMSEA Df diff Pr(>Chisq)    
fit1 48 7484.4 7706.8 115.85                                           
fit2 54 7480.6 7680.8 124.04      8.192 0.049272       6     0.2244    
fit3 60 7508.6 7686.6 164.10     40.059 0.194211       6  4.435e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

In this example, the results indicate that strong invariance does not hold. The main point, however, is to demonstrate that the configural, weak, and strong invariance models can all be specified using the same model syntax, with the group_equal= argument automatically handling the necessary constraints.

The primary objective of this section is to demonstrate how to explicitly specify the configural, weak, and strong invariance models directly in the model syntax, without using the group_equal= argument. Special attention is given to the correct application of modifiers when dealing with multiple groups.

2.6.1 Manual specification of the configural model

The configural model can be specified without modifications, as no constraints are imposed at this stage. However, to prepare for the weak and strong invariance models, intercepts and latent means are explicitly included, and all relevant parameters are labeled.

In multiple-group analyses, all modifiers must be expressed in vector form, as illustrated in the following syntax:

HS_model_configural <- '
    visual  =~ c(1, 1)*x1 + c(la2.1, la2.2)*x2 + c(la3.1, la3.2)*x3
    textual =~ c(1, 1)*x4 + c(la5.1, la5.2)*x5 + c(la6.1, la6.2)*x6
    speed   =~ c(1, 1)*x7 + c(la8.1, la8.2)*x8 + c(la9.1, la9.2)*x9

    # ov intercepts
    x1 ~ c(i1.1, i1.2)*1
    x2 ~ c(i2.1, i2.2)*1
    x3 ~ c(i3.1, i3.2)*1
    x4 ~ c(i4.1, i4.2)*1
    x5 ~ c(i5.1, i5.2)*1
    x6 ~ c(i6.1, i6.2)*1
    x7 ~ c(i7.1, i7.2)*1
    x8 ~ c(i8.1, i8.2)*1
    x9 ~ c(i9.1, i9.2)*1

    # lv means (optional, zero by default)
    visual  ~ c(0, 0)*1
    textual ~ c(0, 0)*1
    speed   ~ c(0, 0)*1
'
fit1b <- sem(HS_model_configural, data = HolzingerSwineford1939,
             group = "school")

The c(1, 1)* modifier in the first formula fixes the first factor loading to 1 in both groups. If the loading should be fixed in the first group but freely estimated in the second, c(1, NA)* would be used, with NA indicating a freely estimated parameter.

Subsequent terms, such as c(la2.1, la2.2)*, assign labels to factor loadings for each observed indicator, with the suffix .1 denoting the first group and .2 the second. Because the labels differ across groups, no equality constraints are imposed. The same labeling approach is applied to intercepts (i1, i2, etc.), maintaining independence between groups.

Finally, latent variable means are explicitly fixed to zero in both groups. While these means would default to zero without constraints, specifying them explicitly establishes a clear foundation for subsequent steps in the measurement invariance testing process.

2.6.2 Manual specification of the weak invariance model

The weak invariance model is specified by constraining factor loadings to be equal across groups:

HS_model_weak <- '
  visual  =~ c(1, 1)*x1 + c(la2, la2)*x2 + c(la3, la3)*x3
  textual =~ c(1, 1)*x4 + c(la5, la5)*x5 + c(la6, la6)*x6
  speed   =~ c(1, 1)*x7 + c(la8, la8)*x8 + c(la9, la9)*x9

  # ov intercepts
  x1 ~ c(i1.1, i1.2)*1
  x2 ~ c(i2.1, i2.2)*1
  x3 ~ c(i3.1, i3.2)*1
  x4 ~ c(i4.1, i4.2)*1
  x5 ~ c(i5.1, i5.2)*1
  x6 ~ c(i6.1, i6.2)*1
  x7 ~ c(i7.1, i7.2)*1
  x8 ~ c(i8.1, i8.2)*1
  x9 ~ c(i9.1, i9.2)*1
  
  # lv means (optional, zero by default)
  visual  ~ c(0, 0)*1
  textual ~ c(0, 0)*1
  speed   ~ c(0, 0)*1
'
fit2b <- sem(HS_model_weak, data = HolzingerSwineford1939,
             group = "school")

By assigning the same label to a loading in both groups (e.g., la2 instead of la2.1 and la2.2), equality constraints are automatically imposed, satisfying the requirements of the weak invariance model. All other parts of the syntax, including intercepts and latent means, remain the same as in the configural model.

2.6.3 Manual specification of the strong invariance model

The strong invariance model extends the weak invariance model by also constraining the intercepts to be equal across groups. This is achieved by removing the group-specific suffixes from the intercept labels (e.g., i1 instead of i1.1 and i1.2):

HS_model_strong <- '
  visual  =~ c(1, 1)*x1 + c(la2, la2)*x2 + c(la3, la3)*x3
  textual =~ c(1, 1)*x4 + c(la5, la5)*x5 + c(la6, la6)*x6
  speed   =~ c(1, 1)*x7 + c(la8, la8)*x8 + c(la9, la9)*x9

  # ov intercepts
  x1 ~ c(i1, i1)*1
  x2 ~ c(i2, i2)*1
  x3 ~ c(i3, i3)*1
  x4 ~ c(i4, i4)*1
  x5 ~ c(i5, i5)*1
  x6 ~ c(i6, i6)*1
  x7 ~ c(i7, i7)*1
  x8 ~ c(i8, i8)*1
  x9 ~ c(i9, i9)*1

  # lv means
  visual  ~ c(0, NA)*1
  textual ~ c(0, NA)*1
  speed   ~ c(0, NA)*1
'
fit3b <- sem(HS_model_strong, data = HolzingerSwineford1939,
             group = "school")

Note that the latent means are specified to be fixed at zero in the first group (serving as the reference) and freely estimated in the second group using NA. This allows the estimated means in the second group to be interpreted as deviations from the reference group, assuming strong invariance holds. The fitted models fit1b, fit2b, and fit3b are equivalent to fit1, fit2, and fit3, respectively.

2.6.4 More on modifiers with multiple groups

In lavaan, using the same label across groups causes the corresponding parameter to be constrained equal in all groups. If the labels differ, each group receives its own freely estimated value. For example, in a five-group analysis, the following syntax:

f ~ c(a,a,b,b,b)*1

constrains the mean of f to be equal in groups 1 and 2 (labeled a) and equal in groups 3 through 5 (labeled b), while allowing differences between these two clusters.

This principle applies to all modifiers, not just labels. For instance, group-specific starting values can be specified as:

f ~ start(c(0.1, 0.1, 0.1, 0.2, 0.5))*1

In general, it is safest in a multiple-group context to express all modifiers as vectors, ensuring explicit control over group-specific values.

lavaan also provides a shorthand for numeric modifiers. Writing:

y ~ 1*x1

fixes the regression coefficient of x1 to 1 in all groups, equivalent to the more explicit:

y ~ c(1, 1, 1, 1, 1)*x1

This shortcut works only for numeric modifiers. Using a single label across groups triggers a warning, since it would impose an equality constraint, which may not align with the user’s intentions.

2.7 Creating blocks using the : operator

A block is a set of model parameters treated as a cohesive unit. In most analyses, there is a single block corresponding to one model and one set of parameters. In multiple-group analyses, each group receives its own block, so the number of blocks equals the number of groups. Similarly, in multilevel models, the number of blocks corresponds to the number of levels, and in multigroup multilevel models, there is one block for every unique combination of group and level.

2.7.1 Defining syntax for multiple groups using the : operator

When fitting the same model across multiple independent groups, it is typically sufficient to specify the model syntax once; lavaan applies it to all groups, optionally imposing constraints across them. However, different models can also be specified for each group using the block operator :, as shown below:

group: 1
  f =~ y1 + y2 + y3
group: 2
  f =~ y1 + y2 + y4
group: 3
  f =~ y1 + y2 + y3 + y4

Here, group appears to the left of the : operator, and the group number to the right corresponds to the ordering of groups in the dataset by default, though this can be modified using the group_label= argument. In this example, a one-factor model is fit to each group, but the indicators vary across groups. From a syntax perspective, the models can differ completely between groups.

Even when the models are identical across groups, the block syntax can be useful. It simplifies the specification of equality constraints by eliminating the need for vector notation. For example, the strong invariance model for the Holzinger & Swineford dataset can be expressed using the block approach as follows:

model <- '
group: 1
  visual  =~ x1 + la2*x2 + la3*x3
  textual =~ x4 + la5*x5 + la6*x6
  speed   =~ x7 + la8*x8 + la9*x9
  # ov intercepts
  x1 ~ i1*1
  x2 ~ i2*1
  x3 ~ i3*1
  x4 ~ i4*1
  x5 ~ i5*1
  x6 ~ i6*1
  x7 ~ i7*1
  x8 ~ i8*1
  x9 ~ i9*1
  # latent means (fixed to zero)
  visual  ~ 0*1
  textual ~ 0*1
  speed   ~ 0*1
group: 2
  visual  =~ x1 + la2*x2 + la3*x3
  textual =~ x4 + la5*x5 + la6*x6
  speed   =~ x7 + la8*x8 + la9*x9
  # ov intercepts
  x1 ~ i1*1
  x2 ~ i2*1
  x3 ~ i3*1
  x4 ~ i4*1
  x5 ~ i5*1
  x6 ~ i6*1
  x7 ~ i7*1
  x8 ~ i8*1
  x9 ~ i9*1
  # latent means (free)
  visual  ~ 1
  textual ~ 1
  speed   ~ 1
'
fit3c <- sem(model, data = HolzingerSwineford1939, group = "school")

This syntax produces a model equivalent to the earlier strong invariance models (fit3 and fit3b) while offering an alternative, more explicit structure.

When examining the parameter table for such a model, both group and block columns appear. The rows of the factor loadings are shown below:

subset(
  parameterTable(fit3c), 
  op == "=~", 
  select = c("lhs", "op", "rhs", "block", "group")
)
       lhs op rhs block group
1   visual =~  x1     1     1
2   visual =~  x2     1     1
3   visual =~  x3     1     1
4  textual =~  x4     1     1
5  textual =~  x5     1     1
6  textual =~  x6     1     1
7    speed =~  x7     1     1
8    speed =~  x8     1     1
9    speed =~  x9     1     1
37  visual =~  x1     2     2
38  visual =~  x2     2     2
39  visual =~  x3     2     2
40 textual =~  x4     2     2
41 textual =~  x5     2     2
42 textual =~  x6     2     2
43   speed =~  x7     2     2
44   speed =~  x8     2     2
45   speed =~  x9     2     2

In this example, the group and block columns are identical because each block corresponds to a single group.

2.7.2 Defining syntax for multilevel models using the : operator

Another key context for using the block operator is in multilevel model specification. The block operator enables the definition of separate models for each level. For example:

model <- '
level: 1
  f =~ y1 + y2 + y3
level: 2
  f =~ y1 + y2 + y3
'
fit_twolevel <- sem(model, data = Demo.twolevel, cluster = "cluster")

Here, the left-hand side of the : operator is the keyword level (in lowercase), and the right-hand side indicates the level number. In a two-level model, level: 1 refers to the within-group level (e.g., students), and level: 2 refers to the between-group level (e.g., schools).

Although the same factor structure is specified at both levels in this example, it is not required. Defining different models for different levels is common and often necessary.

In the parameter table for a multilevel model, both level and block columns appear. The following code extracts the factor loadings (=~) and a selection of the columns:

subset(
  parameterTable(fit_twolevel), 
  op == "=~", 
  select = c("lhs", "op", "rhs", "block", "level")
)
   lhs op rhs block level
1    f =~  y1     1     1
2    f =~  y2     1     1
3    f =~  y3     1     1
12   f =~  y1     2     2
13   f =~  y2     2     2
14   f =~  y3     2     2

In this case, the level and block columns are identical because, by design, each level corresponds to a separate block in multilevel models.

2.7.3 A multigroup multilevel model

Another scenario that requires the : operator is the multigroup multilevel model. In lavaan, this is supported only when the grouping variable is defined at the highest level of the data hierarchy. For example, if students are nested within schools, the grouping variable could be country (e.g., Belgium vs. France), but not an individual-level variable such as student gender.

Suppose a dataset contains schools (identified by the cluster variable) located in either Belgium or France. A grouping variable can be created as follows:

Demo.twolevel$country <- ifelse(
  Demo.twolevel$cluster <= 100, "Belgium", "France"
)

A multigroup multilevel model can then be specified and fitted, estimating a two-level model for each country:

model <- '
group: 1
  level: 1
    f =~ y1 + a*y2 + b*y3
  level: 2
    f =~ y1 + y2 + y3
group: 2
  level: 1
    f =~ y1 + a*y2 + b*y3
  level: 2
    f =~ y1 + y2 + y3
'
fit_block <- sem(model, data = Demo.twolevel, 
                 group = "country", cluster = "cluster")

This syntax defines four blocks: two groups (countries), each with two levels (within and between). In this example, equality constraints across groups are imposed only at the within level (via a and b), but any pattern of constraints (across groups, levels, or both) can be applied.

The resulting parameter table includes block, group, and level columns. The following code extracts the factor loadings:

subset(
  parameterTable(fit_block), 
  op == "=~", 
  select = c("lhs", "op", "rhs", "block", "group", "level")
)
   lhs op rhs block group level
1    f =~  y1     1     1     1
2    f =~  y2     1     1     1
3    f =~  y3     1     1     1
12   f =~  y1     2     1     2
13   f =~  y2     2     1     2
14   f =~  y3     2     1     2
23   f =~  y1     3     2     1
24   f =~  y2     3     2     1
25   f =~  y3     3     2     1
34   f =~  y1     4     2     2
35   f =~  y2     4     2     2
36   f =~  y3     4     2     2

For this model, there are four blocks, two groups, and two levels.

A block identifier may appear more than once in the model syntax. Blocks with the same label (for example, two level: 1 blocks, or two group: 1 blocks) are merged into a single block, as if their formulas had been written together. This is convenient when the syntax is assembled from separate pieces. The role of a variable (for example, whether a covariate is exogenous) is determined from the merged block, not from the piece in which it happens to appear first.

The (open) parser recognizes four keywords on the left-hand side of the : operator: group, level, class, and block. However, only group and level are currently supported by the fitting functions: the class keyword (intended for mixture models) is reserved for future use, and the generic block keyword merely delimits blocks without assigning them a specific role. In addition, other packages may register their own block keywords through the extension mechanism of the open parser (see Section 2.9).

2.8 Indexed names for repeated measures

Models for repeated measures in wide format (one column per variable and per wave: x1, x2, x3, x4) contain many formulas that differ only by the wave. A cross-lagged panel model for two variables measured at four waves, for instance, needs one autoregressive and one cross-lagged effect per variable and per transition, a residual covariance per wave, and a variance per variable and per wave, all written out by hand. An index in square brackets writes such a family of formulas once.

2.8.1 Binding and referring to an index

The index is bound to a range of integers in one place of a formula, and can be referred to elsewhere in the same formula, possibly with an integer offset:

wx[t in 2:4] ~ wx[t-1] + wy[t-1]

The formula stands for one copy per value of the index, in which every indexed name is written with the value directly after it:

wx2 ~ wx1 + wy1
wx3 ~ wx2 + wy2
wx4 ~ wx3 + wy3

The expansion happens before anything else (before the ++ operator and before the formula is flattened), so that the parameter table contains the ordinary wide names, exactly as if the three formulas had been written by hand:

lavParseModelString(model_syntax = 'wx[t in 2:4] ~ wx[t-1] + wy[t-1]',
                    as_data_frame = TRUE)[, c("lhs", "op", "rhs")]
  lhs op rhs
1 wx2  ~ wx1
2 wx2  ~ wy1
3 wx3  ~ wx2
4 wx3  ~ wy2
5 wx4  ~ wx3
6 wx4  ~ wy3

The rules are as follows. An index is bound once per formula, on any name of the formula (left- or right-hand side); referring to an index that is not bound in the formula, or binding it twice, is an error. A range lo:hi is ascending. Several indices may be bound in one formula, and the copies then run over all combinations of their values. A bound may also be an index bound earlier in the same formula, alone or with an offset in parentheses: x[s in 1:2] ~~ x[t in (s+1):3] gives each pair once (x1 ~~ x2, x1 ~~ x3, and x2 ~~ x3), and a dependent range that comes out empty generates nothing. The value is written directly after the name in front of the bracket (x1_[t] gives x1_3); there is no space between a name and its index, and no text after the closing bracket. If the lower bound of a range is written with a leading zero, all generated names use that width: y[t in 03:10] ~ y[t-1] gives y03 ~ y02 up to y10 ~ y09. Nothing is dropped silently: a range that is too wide generates names that do not exist in the data (such as wx0), and lavaan reports them as missing variables. The endpoints of the ++ operator cannot be indexed names, and a quoted name is never expanded.

2.8.2 Labels, constraints, and defined parameters

Labels are names, and can carry an index as well. A label without an index is repeated in every copy, which implies an equality constraint across the waves; a label with an index gives one label per wave:

lavParseModelString(
  model_syntax = 'wx[t in 2:4] ~ a*wx[t-1] + b[t]*wy[t-1]',
  as_data_frame = TRUE)[, c("lhs", "op", "rhs", "label")]
  lhs op rhs label
1 wx2  ~ wx1     a
2 wx2  ~ wy1    b2
3 wx3  ~ wx2     a
4 wx3  ~ wy2    b3
5 wx4  ~ wx3     a
6 wx4  ~ wy3    b4

The autoregressive effect is the same at every transition (label a, three times), while the cross-lagged effects are free (labels b2, b3, and b4). Indexed labels can then be used in constraints and in definitions, which are expanded in the same way:

wx[t in 2:4] ~ a[t]*wx[t-1]    # labels a2, a3, a4
a[t in 2:3] == a[t+1]          # a2 == a3, a3 == a4
d[t in 2:3] := a[t+1] - a[t]   # d2 := a3 - a2, d3 := a4 - a3

2.8.3 Index values as numbers

Inside a modifier (or in a constraint or a definition), a bound index that is used as a number stands for its value. This gives, for example, the fixed time scores of a linear growth model in a single formula:

lavParseModelString(model_syntax = 's =~ (t-1)*y[t in 1:5]',
                    as_data_frame = TRUE)[, c("lhs", "op", "rhs", "fixed")]
  lhs op rhs fixed
1   s =~  y1     0
2   s =~  y2     1
3   s =~  y3     2
4   s =~  y4     3
5   s =~  y5     4

A bare index as the whole modifier (t*y[t]) would read as a label, which is not allowed (the error message says so); write fixed(t)*y[t] instead.

2.8.4 A random-intercept cross-lagged panel model

The random-intercept cross-lagged panel model (Hamaker et al., 2015) for two variables measured at four waves decomposes each observed score into a stable, person-level random intercept and a wave-specific within-person deviation, and regresses the deviations on those of the previous wave. We generate data from this model (chapter 19 explains lavSimulateData()); the population syntax is itself a compact illustration of indexed names with fixed values:

pop_riclpm <- '
  # random intercepts
    RIx =~ 1*x[t in 1:4]
    RIy =~ 1*y[t in 1:4]
  # within-person components
    wx[t in 1:4] =~ 1*x[t]
    wy[t in 1:4] =~ 1*y[t]
    x[t in 1:4] ~~ 0*x[t]
    y[t in 1:4] ~~ 0*y[t]
  # autoregressive and cross-lagged effects
    wx[t in 2:4] ~ 0.4*wx[t-1] + 0.2*wy[t-1]
    wy[t in 2:4] ~ 0.1*wx[t-1] + 0.5*wy[t-1]
  # (residual) variances and covariances
    wx1 ~~ 1*wx1 + 0.3*wy1
    wy1 ~~ 1*wy1
    wx[t in 2:4] ~~ 0.8*wx[t] + 0.2*wy[t]
    wy[t in 2:4] ~~ 0.7*wy[t]
    RIx ~~ 0.5*RIx + 0.2*RIy
    RIy ~~ 0.5*RIy
    RIx + RIy ~~ 0*wx1 + 0*wy1
'
Wide <- lavSimulateData(pop_riclpm, sample_nobs = 500, seed = 1234)
head(Wide, 3)
          x1          x2         x3         x4         y1         y2
1 -1.3644932  0.04034502 -1.1692483  0.9262524 -2.1225991 -2.3644673
2 -0.2862587 -1.35803342 -0.4976739 -1.7188969 -0.1351364  0.2205352
3  0.8532826  0.24033262 -1.5786800 -1.0747442 -0.4678251 -1.3177525
           y3         y4
1 -1.82290135 -2.5364016
2  0.08747192 -0.9683721
3 -0.40827696 -0.3888921

The last line of the population syntax fixes the covariances between the random intercepts and the first-wave within components to zero; without it, these four covariances between exogenous latent variables would be free in the fitted model as well (see the automatic additions of chapter 3). The model is the same syntax with the fixed values removed:

model_riclpm <- '
  # random intercepts
    RIx =~ 1*x[t in 1:4]
    RIy =~ 1*y[t in 1:4]
  # within-person components
    wx[t in 1:4] =~ 1*x[t]
    wy[t in 1:4] =~ 1*y[t]
    x[t in 1:4] ~~ 0*x[t]
    y[t in 1:4] ~~ 0*y[t]
  # autoregressive and cross-lagged effects
    wx[t in 2:4] ~ wx[t-1] + wy[t-1]
    wy[t in 2:4] ~ wx[t-1] + wy[t-1]
  # (residual) variances and covariances
    wx[t in 1:4] ~~ wx[t] + wy[t]
    wy[t in 1:4] ~~ wy[t]
    RIx ~~ RIx + RIy
    RIy ~~ RIy
    RIx + RIy ~~ 0*wx1 + 0*wy1
'
fit_riclpm <- sem(model_riclpm, data = Wide)
fitMeasures(fit_riclpm, c("chisq", "df", "pvalue"))
 chisq     df pvalue 
 5.091  9.000  0.826 
subset(parameterEstimates(fit_riclpm), op == "~")
   lhs op rhs   est    se     z pvalue ci.lower ci.upper
25 wx2  ~ wx1 0.380 0.058 6.518  0.000    0.266    0.494
26 wx2  ~ wy1 0.248 0.050 4.968  0.000    0.150    0.346
27 wx3  ~ wx2 0.242 0.079 3.060  0.002    0.087    0.396
28 wx3  ~ wy2 0.312 0.069 4.513  0.000    0.176    0.447
29 wx4  ~ wx3 0.340 0.079 4.334  0.000    0.186    0.494
30 wx4  ~ wy3 0.205 0.064 3.182  0.001    0.079    0.331
31 wy2  ~ wx1 0.081 0.057 1.433  0.152   -0.030    0.193
32 wy2  ~ wy1 0.478 0.062 7.757  0.000    0.357    0.599
33 wy3  ~ wx2 0.180 0.068 2.630  0.009    0.046    0.313
34 wy3  ~ wy2 0.458 0.076 6.016  0.000    0.309    0.608
35 wy4  ~ wx3 0.075 0.063 1.189  0.234   -0.049    0.198
36 wy4  ~ wy3 0.553 0.059 9.346  0.000    0.437    0.669

Replacing the free regression coefficients by the labels a, b, c, and d (without an index) gives the model with time-invariant effects, and the two models can be compared with a likelihood ratio test (chapter 11):

model_riclpm_eq <- '
    RIx =~ 1*x[t in 1:4]
    RIy =~ 1*y[t in 1:4]
    wx[t in 1:4] =~ 1*x[t]
    wy[t in 1:4] =~ 1*y[t]
    x[t in 1:4] ~~ 0*x[t]
    y[t in 1:4] ~~ 0*y[t]
    wx[t in 2:4] ~ a*wx[t-1] + b*wy[t-1]
    wy[t in 2:4] ~ c*wx[t-1] + d*wy[t-1]
    wx[t in 1:4] ~~ wx[t] + wy[t]
    wy[t in 1:4] ~~ wy[t]
    RIx ~~ RIx + RIy
    RIy ~~ RIy
    RIx + RIy ~~ 0*wx1 + 0*wy1
'
fit_riclpm_eq <- sem(model_riclpm_eq, data = Wide)
lavTestLRT(fit_riclpm_eq, fit_riclpm)
Chi-Squared Difference Test

              Df   AIC   BIC   Chisq Chisq diff    RMSEA Df diff Pr(>Chisq)
fit_riclpm     9 11029 11143  5.0907                                       
fit_riclpm_eq 17 11025 11105 16.7496     11.659 0.030244       8     0.1671

2.8.5 The lag column of the parameter table

The index of a generated name is retained. For every element of the parameter table that comes from a formula in which the left- and the right-hand side carry the same index, the column lag holds the difference between the index values of the two sides: 1 for wx2 ~ wx1, 0 for wx2 ~~ wy2, and NA for all other elements. The column is only present when the syntax uses indexed names.

subset(parTable(fit_riclpm), op == "~" | lhs == "wx2",
       select = c("lhs", "op", "rhs", "free", "lag"))
   lhs op rhs free lag
10 wx2 =~  x2    0   0
25 wx2  ~ wx1    1   1
26 wx2  ~ wy1    2   1
27 wx3  ~ wx2    3   1
28 wx3  ~ wy2    4   1
29 wx4  ~ wx3    5   1
30 wx4  ~ wy3    6   1
31 wy2  ~ wx1    7   1
32 wy2  ~ wy1    8   1
33 wy3  ~ wx2    9   1
34 wy3  ~ wy2   10   1
35 wy4  ~ wx3   11   1
36 wy4  ~ wy3   12   1
39 wx2 ~~ wx2   15   0
40 wx2 ~~ wy2   16   0

2.8.6 Long data: the panel argument

Repeated measures are often stored in long format, with one row per person and occasion. The panel argument of the fitting functions names the id and the time variable, and lavaan then reshapes the data to the wide format before the analysis, so that the model is written for the wide variables, by name or with indexed names:

Long <- reshape(cbind(id = seq_len(nrow(Wide)), Wide), direction = "long",
                varying = list(paste0("x", 1:4), paste0("y", 1:4)),
                v.names = c("x", "y"), timevar = "wave", idvar = "id",
                times = 1:4)
head(Long[order(Long$id, Long$wave), ], 5)
    id wave           x          y
1.1  1    1 -1.36449317 -2.1225991
1.2  1    2  0.04034502 -2.3644673
1.3  1    3 -1.16924826 -1.8229014
1.4  1    4  0.92625244 -2.5364016
2.1  2    1 -0.28625871 -0.1351364
fit_long <- sem(model_riclpm, data = Long,
                panel = c(id = "id", time = "wave"))
all.equal(coef(fit_long), coef(fit_riclpm))
[1] TRUE

The variable x at time 3 becomes x3 (an optional sep element puts a separator between the name and the time: panel = c(id = "id", time = "wave", sep = "_") gives x_3). Occasions without a row become missing values, to be handled with missing = "ml". The details of the reshape (time-invariant covariates, grouping and cluster variables, the ordered and aux arguments) are described with the other data arguments in chapter 5 (Section 5.1.5). For a two-level model (with level: blocks), the long data are not reshaped: each row is an occasion, the id variable is the cluster variable, and an index that is not bound, as in y ~ y[t-1], then refers to the value of y at the previous occasion of the same person. These lagged variables are the subject of Section 16.14 in the multilevel chapter.

2.9 Implementation notes

This section collects details that are tied to the current implementation of lavaan (the R package, version 0.7-4) rather than to the model syntax itself, and that may therefore change at any release.

The first note concerns the :~ operator, which defines a data-defined (or moderated) parameter. It redefines an existing, labeled free parameter as a per-observation function of one or more observed variables (each wrapped in data()) and a set of new component parameters. For example, given f =~ y1 + L2*y2 + y3, the line L2 :~ L2_0 + L2_1 * data(z) lets the loading L2 vary linearly with the moderator z; the components L2_0 and L2_1 become free parameters. A definition may also depend on the data indirectly, through another :~ definition (L3 :~ 0.5 * L2 + L3_0, with L2 itself data-defined); a definition that involves neither data() nor another definition is refused, since a parameter that is a function of other parameters only is defined with :=. Note the contrast with a random slope (rv()): a random slope varies across clusters as a latent variable, whereas a :~ parameter varies deterministically with observed variables.

Because the definition involves the data, the model has one set of model-implied moments per observation, and estimating it requires a casewise likelihood. As of version 0.7-4, lavaan does not compute that likelihood itself. It parses and stores the specification (the parameter table, starting values, and a per-observation evaluation function), forces a mean structure (a casewise likelihood always involves the means), removes the cases with a missing value on a definition variable (regardless of the missing argument; with a warning unless missing = "listwise"), and leaves the estimation to an external backend. A backend registered with lavBackendRegister() can be named in the backend argument, in which case lavaan prepares the model, calls the backend, and imports its results into an ordinary fitted object; alternatively, do_fit = FALSE returns the prepared object, and lavImportResults() builds the fitted object from estimates obtained elsewhere. Everything that derives from a single moment structure (fitted moments, residuals, modification indices, the standardized solution, factor scores, the chi-square test and the fit indices) is refused for these models, whereas the estimates, standard errors, log-likelihood, information criteria, and likelihood ratio tests between nested models of this class are available once a backend has estimated the model. In the parameter table, the moderated parameter keeps its row (its estimate is shown as (:~) in the summary() output, since it has no single value), and the components are added as rows with the operator dp; lavInspect(fit, "list_unmoderated") returns the parameter table of the model without the definitions, with the moderated parameters free again.

The second note concerns the expressions that may appear inside the model syntax: as fixed parameter values (y ~ x1 + log(3)*x2), on the right-hand side of := definitions, and on either side of the ==, <, and > constraint operators. In the R package, these fragments are handed to R’s own evaluator, so any valid R expression can be used, including calls to functions defined in the user’s workspace. It is worth distinguishing two cases, however. Simple arithmetic with standard mathematical functions (sqrt, exp, log, …), which covers nearly all usage in practice, is portable: it has the same meaning regardless of the language in which the syntax is read. Expressions beyond that (say, dnorm(0.3), or a call to a user-defined function) work only because the host language happens to be R, and they are meaningless to the many other programs that read lavaan syntax (GUI front-ends, converters, SEM software in other languages). Model syntax that stays within the portable subset is therefore easier to reuse, by collaborators using other front-ends today and in other host languages in the future.

The third note concerns the syntax parser itself. Over the years, lavaan has featured several generations of syntax parsers. The original parser (parser = "old") served until version 0.6-18, when it was replaced by a completely rewritten parser (parser = "new"). Since version 0.7-2, the default is a third parser: parser = "open". For standard model syntax, the open parser behaves like its predecessor, but it is extensible: other R packages can register their own operators, modifiers, and block keywords (see the help page ?open_parser). The parser= argument (of lavParseModelString(), but also of lavaan(), cfa(), and sem()) can be used to switch back to an older parser if needed. Indexed names (Section 2.8) are only known to the open parser, which expands them on the tokens of each formula before the ++ expansion; the lag column of the parameter table is passed from the parser to lavaanify() as an internal modifier. The reshape of long panel data (panel=) happens right after the model has been parsed (so that only the wide variables the model uses are created), in lav_data_panel.R; lagged variables for two-level models are added to the data in the same step.

These parser generations are implementation history; the language they parse has remained the same, and it is the language, not any particular parser, that the many programs reading lavaan syntax (GUI front-ends, converters, SEM software in other languages) rely on. The syntax described in this chapter is perhaps, in that sense, the most durable part of the whole package.