Learn R Programming

piecewiseSEM: Piecewise Structural Equation Modeling in R

Version 2.3.1

Last updated: 02 September 2025

To install

Run the following code to install the latest version from CRAN:

install.packages("piecewiseSEM")

Run the following code to install the development version:

devtools::install_github("jslefche/piecewiseSEM@devel")

Note: the development version may be unstable and lead to unanticipated bugs. Contact the package developer via Github with any bugs or issues.

Getting Help

See our website at piecewiseSEM

There is an online resource available for SEM, including piecewiseSEM and lavaan, available https://jslefche.github.io/sem_book/

Version 2 is a major update to the piecewiseSEM package that uses a completely revised syntax that better reproduces the base R syntax and output. It is highly recommended that consult the resource above even if you have used the package before as it documents the many changes.

Currently supported model classes: lm, glm, gls, Sarlm, lme, glmmPQL, lmerMod, merModLmerTest, glmerMod. glmmTMB, gam

Example

# Load library
library(piecewiseSEM)

# Create fake data
set.seed(1)

data <- data.frame(
  x = runif(100),
  y1 = runif(100),
  y2 = rpois(100, 1),
  y3 = runif(100)
)

# Create SEM using `psem`
modelList <- psem(
  lm(y1 ~ x, data),
  glm(y2 ~ x, "poisson", data),
  lm(y3 ~ y1 + y2, data),
  data
)

# Run summary
summary(modelList)

# Address conflict using conserve = T
summary(modelList, conserve = T)

# Address conflict using direction = c()
summary(modelList, direction = c("y2 <- y1"))

# Address conflict using correlated errors
modelList2 <- update(modelList, y2 %~~% y1)

summary(modelList2)

Copy Link

Version

Install

install.packages('piecewiseSEM')

Monthly Downloads

1,624

Version

2.3.1

License

GPL-3

Maintainer

Jon Lefcheck

Last Published

September 2nd, 2025

Functions in piecewiseSEM (2.3.1)

basisSet

Derivation of the basis set
handleCategoricalCoefs

Handles putting categorical variables into coefficient tables for easy use in path analysis
import

Functions to import from dependencies
getDAG

Generate adjacency matrix from list of structural equations
evaluateClasses

Evaluate model classes and stop if unsupported model class
coefs

Extract path coefficients
cbind_fill

Bind data.frames of differing dimensions
multigroup

Multigroup Analysis for Piecewise SEM
partialResid

Computing partial effects
getCoefficients

Get coefficients from linear regression
filterExisting

Remove existing paths from the basis set
dupOutput

Identify duplicate output
findbars.lme

Get random effects from lme
anovaLRT

Chi-square difference test
checkData

Check to see whether supplied data.frame matches model-extracted data
checkTransformations

Check to see whether variables exist as transformed and untransformed
all_vars_notrans

Get vector of untransformed variables
print.summary.psem

Print summary
%~~%

Correlated error operator
nObs

Get number of observations from a model
onlyBars

Get random effects from merMod
getSortedPsem

Get a sorted psem object in DAG order
piecewiseSEM-package

The 'piecewiseSEM` package
get_response

Get Response Name as a Character
meadows

Data set from Grace & Jutila (1999)
filterSmoothed

First, remove claims where linear and non-linear terms appear in the same claim
fisherC

Summarize tests of directed separation using Fisher's C statistic
psem

Fitting piecewise structural equation models
print.basisSet

Print basis set
print.anova.psem

Print anova
plot.psem

Plotting of Piecewise Structural Equation Models
residuals.psem

Residual values from fit models
rsquared

R-squared for linear regression
listFormula

Recompute P-values using Kenward-Rogers approximation
print.psem

Print psem
keeley

Data set from Grace & Keeley (2006)
stripTransformations

Strip transformations
getRHS

Get Right-hand side of formulae
filterInteractions

Filter interactions from the d-sep tests
partialCorr

Calculate partial correlations from partial residuals
rsquared.gam

R^2 for gam objects
sortDag

Sort DAG based on ancestry
print.multigroup.psem

Print multigroup
summary.psem

Summarizing piecewise structural equation models
rsquared.negbin

R^2 for negbin objects
getAnova

Get ANOVA results from `merMod`
isSig

Assess significance
scaleGLM

Compute standard deviation or relevant range of response for GLMs
getSatModels

Get saturated model by reinserting all excluded paths
%not_in%

Operator for non-overlap in sets
reverseAddVars

Replace transformations in the basis set by cycling through neighbors and applying transformations in order of how variables are treated in the child nearest to current node
filterExogenous

Filter relationships among exogenous variables from the basis set (ignoring add.vars)
removeCerror

Remove correlated errors from the basis set
rsquared.glmerMod

R^2 for glmer objects
removeData

Remove data from the model list
rsquared.glm

R^2 for glm objects
specifyDir

Remove duplicate items from the basis set whose direction is not a priori specified
update.psem

Update psem model object with additional values.
shipley

Data set from Shipley (2006)
reverseNonLin

If intermediate endogenous variables are nonlinear, return both directions
fixCatDir

Flip independence claims so categorical variables are not the response
getResidModels

Identify models with correlated errors and return modified versions
print.attr

Do not print attributes with custom functions
rsquared.gls

R^2 for gls objects
stop_psem

Stop function for unsupported methods
stdCoefs

Calculate standardized regression coefficients
rsquared.lme

R^2 for lme objects
rsquared.lm

R^2 for lm objects
unstdCoefs

Get raw (undstandardized) coefficients from model
scaleInt

Calculate standard deviation or relevant range for interaction terms
rsquared.Sarlm

R^2 for Sarlm objects
testBasisSetElements

Evaluate conditional independence claim from the basis set
rsquared.merMod

R^2 for phylolm objects
rsquared.glmmPQL

R^2 for glmmPQL objects
resid.lme

Get residuals from innermost grouping of mixed models (replicate-level)
GetSDx

Get standard deviation of predictor variables
LLchisq

Generalized chi-squared for piecewise SEM
AIC.psem

Generic function for SEM AIC(c) score
AIC_psem

Information criterion values for SEM
as.psem

Convert list to psem object
cerror

Correlated errors
dSep

Tests of directed separation
anova.psem

ANOVA and chi-squared difference test for model comparison
getLHS

Get Left-hand side of formulae
all_vars_merMod

Remove random effects from all.vars
GetOLRE

Obtain (observation-level) random effects from a generalized linear mixed model
GetSingleData

Get data from one model
GetVarCov

Get random effects variance-covariance from lme
all_vars_trans

Get vector of transformed variables
captureTable

Captures output table
GetData

Get data from model list
formatpsem

Format for psem
GetSDy

Properly scale standard deviations depending on the error distribution
anovaTable

Single anova
dataTrans

Transform variables based on model formula and store in new data frame