Learn R Programming

SEMinR allows users to easily create and modify structural equation models (SEM). It allows estimation using either covariance-based SEM (CBSEM, such as LISREL/Lavaan), or Partial Least Squares Path Modeling (PLS-PM, such as SmartPLS/semPLS).

First Look

Main features of using SEMinR:

  • A natural feeling, domain-specific language to build and estimate SEMs in R
  • High-level functions to quickly specify interactions and complicated structural models
  • Modular design of models that promotes reuse of model components
  • Encourages best practices by use of smart defaults and warnings

Take a look at the easy syntax and modular design:

# Define measurements with famliar terms: reflective, composite, multi-item constructs, etc.
measurements <- constructs(
  reflective("Image",       multi_items("IMAG", 1:5)),
  composite("Expectation", multi_items("CUEX", 1:3)),
  composite("Loyalty",     multi_items("CUSL", 1:3), weights = mode_B),
  composite("Complaints",  single_item("CUSCO"))
)

# Create four relationships (two regressions) in one line!
structure <- relationships(
  paths(from = c("Image", "Expectation"), to = c("Complaints", "Loyalty"))
)

# Estimate the model using PLS estimation scheme (Consistent PLS for reflectives)
pls_model <- estimate_pls(data = mobi, measurements, structure)
#> Generating the seminr model
#> All 250 observations are valid.

# Re-estimate the model as a purely reflective model using CBSEM
cbsem_model <- estimate_cbsem(data = mobi, as.reflective(measurements), structure)
#> Generating the seminr model for CBSEM

SEMinR can plot models using the semplot (for CBSEM models) or DiagrammeR (for PLS models) packages with a simple plot method.

plot(pls_model, title = "PLS Model")
save_plot("myfigure.pdf")

SEMinR allows various estimation methods for constructs and SEMs:

  • Covariance-based Structural Equation Modeling (CBSEM)
    • Covariance-based estimation of SEM using the popular Lavaan package
    • Currently supports mediation and moderation models with constructs
    • Easily specify interactions between constructs
    • Adds ten Berge factor score extraction to get same correlation patterns as latent factors
    • Adds VIF and other validity assessments
  • Confirmatory Factor Analysis (CFA) using Lavaan
    • Uses Lavaan package and returns results and syntax
    • Adds ten Berge factor score extraction to get same correlation patterns as latent factors
  • Partial Least Squares Path Modeling (PLS-PM)
    • Uses non-parametric variance-based estimation to construct composites and common-factors
    • Automatically estimates using Consistent PLS (PLSc) when emulating reflective common factors
    • Adjusts for known biases in interaction terms in PLS models
    • Continuously tested against leading PLS-PM software to ensure parity of outcomes: SmartPLS, ADANCO, semPLS, and matrixpls
    • High performance, multi-core bootstrapping function

Researchers can now create a SEM and estimate it using different techniques (CBSEM, PLS-PM).

Installation

You can install SEMinR from R with:

install.packages("seminr")

Usage and Examples

Load the SEMinR package:

library(seminr)

Describe measurement and structural models and then estimate them. See the various examples below for different use cases:

  1. CFA + CBSEM Example with Common Factors
  2. Consistent-PLS (PLSc) Example with Common Factors
  3. PLS-PM Example with Composites
  4. Comparing CBSEM and PLS-PM Example

CFA + CBSEM Example with Common Factors

Note that CBSEM models reflective common-factor constructs, not composites. SEMinR uses the powerful Lavaan package to estimate CBSEM models – you can even inspect the more complicated Lavaan syntax that is produced.

Describe reflective constructs and interactions:

# Distinguish and mix composite or reflective (common-factor) measurement models
# - composite measurements will have to be converted into reflective ones for CBSEM (see below)
measurements <- constructs(
  reflective("Image",       multi_items("IMAG", 1:5)),
  reflective("Expectation", multi_items("CUEX", 1:3)),
  interaction_term(iv = "Image", moderator = "Expectation", method = two_stage),
  reflective("Loyalty",     multi_items("CUSL", 1:3)),
  reflective("Complaints",  single_item("CUSCO"))
)

Describe the causal relationships between constructs and interactions:

# Quickly create multiple paths "from" and "to" sets of constructs
structure <- relationships(
  paths(from = c("Image", "Expectation", "Image*Expectation"), to = "Loyalty"),
  paths(from = "Image", to = c("Complaints"))
)

Put the above elements together to estimate the model using Lavaan:

# Evaluate only the measurement model using Confirmatory Factor Analysis (CFA)
cfa_model <- estimate_cfa(data = mobi, measurements)
summary(cfa_model)

# Dynamically compose full SEM models from individual parts
# - if measurement model includes composites, convert all constructs to reflective using:
#     as.reflective(measurements)
cbsem_model <- estimate_cbsem(data = mobi, measurements, structure)
sum_cbsem_model <- summary(cbsem_model)
sum_cbsem_model$meta$syntax # See the Lavaan syntax if you wish

Consistent-PLS (PLSc) Example with Common Factors

Models with reflective common-factor constructs can also be estimated in PLS-PM, using Consistent-PLS (PLSc). Note that the popular SmartPLS software models constructs as composites rather than common-factors (see below) but can also do PLSc as a special option.

We will reuse the measurement and structural models from earlier:

# Optionally inspect the measuremnt and structural models
measurements
structure

Estimate full model using Consistent-PLS and bootstrap it for confidence intervals:

# Models with reflective constructs are automatically estimated using PLSc
pls_model <- estimate_pls(data = mobi, measurements, structure)
summary(pls_model)

# Use multi-core parallel processing to speed up bootstraps
boot_estimates <- bootstrap_model(pls_model, nboot = 1000, cores = 2)
summary(boot_estimates)

PLS-PM Example with Composites

PLS-PM typically models composites (constructs that are weighted average of items) rather than common factors. Popular software like SmartPLS models composites either as Mode A (correlation weights) or Mode B (regression weights). We also support both modes as well as second-order composites. rather than common factors. Popular software like SmartPLS models composites by default, either as Mode A (correlation weights) or Mode B (regression weights). We also support second-order composites.

Describe measurement model for each composite, interaction, or higher order composite:

# Composites are Mode A (correlation) weighted by default
mobi_mm <- constructs(
  composite("Image",        multi_items("IMAG", 1:5)),
  composite("Value",        multi_items("PERV", 1:2)),
  higher_composite("Satisfaction", dimensions = c("Image","Value"), method = two_stage),
  composite("Expectation",  multi_items("CUEX", 1:3)),
  composite("Quality",      multi_items("PERQ", 1:7), weights = mode_B),
  composite("Complaints",   single_item("CUSCO")),
  composite("Loyalty",      multi_items("CUSL", 1:3), weights = mode_B)
)

Define a structural (inner) model for our PLS-PM:

mobi_sm <- relationships(
  paths(from = c("Expectation","Quality"),  to = "Satisfaction"),
  paths(from = "Satisfaction", to = c("Complaints", "Loyalty"))
)

Estimate full model using PLS-PM and bootstrap it for confidence intervals:

pls_model <- estimate_pls(
  data = mobi,
  measurement_model = mobi_mm,
  structural_model = mobi_sm
)

summary(pls_model)

# Use multi-core parallel processing to speed up bootstraps
boot_estimates <- bootstrap_model(pls_model, nboot = 1000, cores = 2)
summary(boot_estimates)

Plotting the model results

SEMinR can plot all supported models using the dot language and the graphViz.js widget from the DiagrammeR package.

# generate a small model for creating the plot
mobi_mm <- constructs(
  composite("Image",        multi_items("IMAG", 1:3)),
  composite("Value",        multi_items("PERV", 1:2)),
  higher_composite("Satisfaction", dimensions = c("Image","Value"), method = two_stage),
  composite("Quality",      multi_items("PERQ", 1:3), weights = mode_B),
  composite("Complaints",   single_item("CUSCO")),
  reflective("Loyalty",      multi_items("CUSL", 1:3))
)
mobi_sm <- relationships(
  paths(from = c("Quality"),  to = "Satisfaction"),
  paths(from = "Satisfaction", to = c("Complaints", "Loyalty"))
)
pls_model <- estimate_pls(
  data = mobi,
  measurement_model = mobi_mm,
  structural_model = mobi_sm
)
#> Generating the seminr model
#> Generating the seminr model
#> All 250 observations are valid.
#> All 250 observations are valid.
boot_estimates <- bootstrap_model(pls_model, nboot = 100, cores = 1)
#> Bootstrapping model using seminr...
#> SEMinR Model successfully bootstrapped

When we have a model, we can plot it and save the plot to files.

plot(boot_estimates, title = "Bootstrapped Model")
save_plot("myfigure.pdf")

Themes

We can customize the plot using an elaborate theme. Themes can be used for individual plots as a parameter or set as a default. Using the seminr_theme_create() function allows to define different themes.

# Tip: auto complete is your friend in finding all possible themeing options.
thm <- seminr_theme_create(plot.rounding = 2, plot.adj = FALSE, 
                           sm.node.fill = "cadetblue1",
                           mm.node.fill = "lightgray")
# change new default theme - valid until R is restarted
seminr_theme_set(thm)

# the new plot
plot(boot_estimates)

Comparing CBSEM and PLS-PM Example

We can re-estimate a composite PLS-PM model as a common-factor CBSEM. Such a comparison might interest researchers seeking to evaluate how their constructs behave when modeled as composites versus common-factors.

# Define measurements with famliar terms: reflective, multi-item constructs, etc.
measurements <- constructs(
  composite("Image",       multi_items("IMAG", 1:5)),
  composite("Expectation", multi_items("CUEX", 1:3)),
  composite("Loyalty",     multi_items("CUSL", 1:3)),
  composite("Complaints",  single_item("CUSCO"))
)

# Create four relationships (two regressions) in one line!
structure <- relationships(
  paths(from = c("Image", "Expectation"), to = c("Complaints", "Loyalty"))
)

# First, estimate the model using PLS
pls_model <- estimate_pls(data = mobi, measurements, structure)

# Reusable parts of the model to estimate CBSEM results
# note: we are using the `as.reflective()` function to convert composites to common factors
cbsem_model <- estimate_cbsem(data = mobi, as.reflective(measurements), structure)

# Re-estimate the model using common factors in Consistent PLS (PLSc)
pls_model <- estimate_pls(data = mobi, as.reflective(measurements), structure)

Documentation

The vignette for Seminr can be found on CRAN or by running the vignette("SEMinR") command after installation.

Demo code for various use cases with SEMinR can be found in the seminr/demo/ folder or by running commands such as demo("seminr-contained") after installation.

Model Specification:

Model Visualization:

Syntax Style:

Sister Projects

  • seminrstudio: A set of addins for RStudio to simplify using SEMinR.

Partner Projects

We communicate and collaborate with several other open-source projects on SEM related issues.

  • plspm package for R: an early and limited PLS path modeling package for R that inspired the development of SEMinR, among others; it is no longer maintained.
  • plspm package for Python: a well-maintained PLS modeling pakage for Python; it is tested against SEMinR and borrows some syntactic ideas from SEMinR.
  • cSEM: a well-maintained and comprehensive composite analysis project implementing PLS and GSCA for R, using Lavaan style syntax

Contact Us

Facebook Group: https://www.facebook.com/groups/seminr

You will find the developers and other users here who might also be able to help or discuss.

Issue Tracker: https://github.com/sem-in-r/seminr/issues

This is the official place to submit potential bugs or request new features for consideration.

About Us

Primary Authors:

Key Contributors:

And many thanks to the growing number of folks who have reached out with feature requests, bug reports, and encouragement. You keep us going!

Copy Link

Version

Install

install.packages('seminr')

Monthly Downloads

1,563

Version

2.3.4

License

GPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

Nicholas Danks

Last Published

October 13th, 2024

Functions in seminr (2.3.4)

composite

Composite construct measurement model specification
dot_component_mm

Generates the dot code for the measurement model
dot_graph_htmt

Creates a dot string with a network graph of constructs based on HTMT measures
dot_subcomponent_mm

generates the dot code for a subgraph (per construct)
dot_graph

Generate a dot graph from various SEMinR models
csem2seminr

seminr csem2seminr() function
compute_itcriteria_weights

Function to calculate Akaike weights for IT Criteria
corp_rep_data

Measurement Instrument for the Corporate Reputation Model
constructs

Measurement functions
extract_bootstrapped_values

extract bootstrapped statistics from an edge using a row_index
estimate_cfa

seminr estimate_cfa() function
extract_htmt_nodes

Helper function that applies formatting to each construct
cor_rsq

Returns R-sq of a dv given correlation matrix of ivs, dv cors <- cbsem_summary$descriptives$correlations$constructs cor_rsq(cors, dv_name = "Value", iv_names = c("Image", "Quality"))
edge_template_default

The default template for labeling bootstrapped edges
estimate_lavaan_ten_berge

seminr estimate_lavaan_ten_berge() function
edge_template_minimal

A minimal template for labeling bootstrapped edges that only shows the bootstrapped mean value
get_manifest_element_size

Gets the optimal size for manifest elements in the plot
df_xtab_matrix

Cross-tabulates columns of a dataframe into a matrix with NAs for unspecified pairs
corp_rep_data2

A Second Measurement Instrument for the Corporate Reputation Model
get_mm_edge_style

individual styles for measurement model edges
estimate_pls

seminr estimate_pls() function
estimate_pls_mga

Performs PLS-MGA to report significance of path differences between two subgroups of data
orthogonal

orthogonal creates interaction measurement items by using the orthogonalized approach wherein
product_indicator

product_indicator creates interaction measurement items by scaled product indicator approach.
interaction_term

Interaction function
esc_node

Wrap a text in single quotes
package_docs

Create a list of section content from every documentation page from a package
extract_mm_edges

extract mm edges from model for a given index of all constructs
psignr

Format p values for the output and removes trailing numbers when p > .10
influencer_data

Measurement Instrument for the Influencer Model
estimate_cbsem

seminr estimate_cbsem() function
simplePLS

seminr simplePLS Function
reflective

Reflective construct measurement model specification
pvalr

Format p values for the output and removes trailing numbers when p > .10
fSquared

seminr fSquared Function
extract_sm_nodes

Helper function that applies formatting to each construct
single_item

Single-item measurement model specification
get_mm_node_shape

Get a string to insert into a node specification using the themed shape
get_mm_node_style

get global measurement model node style
item_errors

Specifies pair of items, or sets of items, that should covary. Used to specify error covariances for associations.
is_sink

Tests whether the i_th construct is endogenous or not
plot_htmt

Plots a network graph of constructs based on HTMT measures
path_factorial

Inner weighting scheme functions to estimate inner paths matrix
path_weighting

Inner weighting scheme functions to estimate inner paths matrix
extract_mm_nodes

gets the individual nodes and applies formatting
plot_interaction

Function for plotting interaction plot for moderated PLS or CBSEM model
extract_mm_coding

extracts the constructs and their types from the model
extract_mm_edge_value

gets the mm_edge value (loading, weight) for bootstrapped and regular models
mobi

Measurement Instrument for the Mobile Phone Industry
rerun

Reruns a previously specified seminr model/analysis
mode_A

Outer weighting scheme functions to estimate construct weighting.
rho_A

seminr rho_A Function
get_construct_element_size

Gets the optimal size for construct elements in the plot
specify_model

seminr specify_model() function
rerun.pls_model

Reruns a previously specified seminr PLS model
get_construct_type

Returns the type of a construct from a model
save_plot

Saves a SEMinR model plot to file
standardize_safely

Standardize (scale) a matrix/df and report interpretable errors
higher_composite

higher_composite
get_global_htmt_style

Get dot string for global theme options
get_global_style

Get dot string for global theme options
get_value_dependent_sm_edge_style

Formats the style of the structural model edges
get_value_dependent_mm_edge_style

Formats the style of the structural model edges
higher_reflective

higher_reflective
format_endo_node_label

Helps to render a node label for endogenous variables
get_theme_doc

Get Documentation for theme options to use in Addin
format_exo_node_label

Helps to render a node label for exogenous variables
get_sm_node_shape

Get a string to insert into a node specification using the themed shape
last_seminr_plot

Retrieve the last plot to be modified or created.
mean_replacement

Function to clean data of omitted values by mean replacement
plot.reliability_table

Function for plotting the measurement model reliability metrics of a PLS model
node_endo_template_default

The default template for labeling endogenous construct nodes
predict_DA

Predictive Scheme
plot.seminr_model

Plot various SEMinR models
predict_EA

Predictive Scheme
set_last_seminr_plot

Set the last plot to be fetched by lastplot()
node_exo_template_default

The default template for labeling exogenous construct nodes
mode_B

Outer weighting scheme functions to estimate construct weighting.
seminr_theme_old

A theme function for a basic b/w theme
multi_items

Multi-items measurement model specification
predict_pls

Predict_pls performs either k-fold or LOOCV on a SEMinR PLS model and generates predictions
seminr_theme_smart

A colored theme
print.seminr_pls_mga

Summary function for PLS-MGA
seminr_theme_get

Get and set the active theme
relationships

Structural specification functions for seminr package
report_paths

Functions for reporting the Path Coefficients and R2 of endogenous constructs and for generating a scatterplot matrix of construct scores.
seminr_theme_dark

The theme function for an inverted theme on black background.
seminr_theme_create

Create a theme for a seminr graph visualization
unit_weights

Outer weighting scheme functions to estimate construct weighting.
use_construct_weights

Should a construct type use weights or loadings
slope_analysis

Function for plotting a slope analysis for an interaction in a PLS model
total_indirect_ci

seminr total indirect confidence intervals function
specific_effect_significance

seminr specific effect significance function
two_stage

Creates an interaction measurement item using a two-stage approach. The two-stage procedure for both PLS and CBSEM models estimates construct scores in the first stage, and uses them to produce a single-item product item for the interaction term in the second stage. For a PLS model, the first stage uses PLS to compute construct scores. For a CBSEM model, the first stage uses a CFA to produce ten Berge construct scores.
associations

Specifies inter-item covariances that should be supplied to CBSEM estimation (estimate_cbsem) or CFA estimation (estimate_cfa)
as.reflective.measurement_model

Converts all contructs of a measurement model, or just a single construct into reflective factors.
as.reflective.construct

Converts a contruct of a measurement model into a reflective factor.
browse_plot

Open Edotor graphViz Website with the preloaded in the Browser
as.reflective

Converts all contructs of a measurement model, or just a single construct into reflective factors.
as.reflective.interaction

Converts interaction of a measurement model into a reflective factors.
PLSc

seminr PLSc Function
boot_paths_df

Return all path bootstraps as a long dataframe. Columns of the dataframes are specified paths and rows are the estimated coefficients for the paths at each bootstrap iteration.
check_test_plot

A function to create regression plots (maybe not needed?)
bootstrap_model

seminr bootstrap_model Function