make a piecewisesem model in r

To create a piecewise SEM model in R, you will need to install the piecewiseSEM package.

Here is an example code to build a piecewise SEM model:

main.r
# load required packages
library(dplyr)
library(lme4)
library(pbkrtest)
library(nlme)
library(MuMIn)
library(piecewiseSEM)

# read in data
data <- read.csv("data.csv")

# define model formula
model_formula <- y ~ x1 + x2 +
                 a * x3 +
                 b * x4 +
                 c * x5

# build the model
model <- piecewise_model(data = data, model_formula = model_formula, 
                         path_matrix = cbind(c(0, 0, 0, 0, 0, 0), # y
                                             c(0, 1, 1, 0, 0, 0), # x1
                                             c(0, 0, 1, 0, 0, 0), # x2
                                             c(0, 0, 0, 1, 0, 0), # x3
                                             c(0, 0, 0, 0, 1, 0), # x4
                                             c(0, 0, 0, 0, 0, 1)), # x5
                         threshold_matrix = c(0, 10, 20), 
                         threshold_names = c("low", "mid", "high"), 
                         method = "bootstrap", bootstrap = 100)

# summary of model
summary(model)
1041 chars
32 lines

In this example, y is the response variable and x1, x2, x3, x4, and x5 are the predictor variables. We also have three thresholds (10 and 20) applied to x3. The path_matrix describes the hypothesized relationships between the variables, and the method argument specifies whether to use the bootstrap method for standard errors.

The piecewise_model function will estimate the model coefficients and generate a summary.

related categories

gistlibby LogSnag