Skip to contents

Regression example

# Load libraries
library(lavaan)
library(lavaanExtra)

# Define our regression terms
regression <- list(
  mpg = names(mtcars)[2:5],
  disp = names(mtcars)[4:7]
)

# Write the model, and check it
mtcars.model <- write_lavaan(regression = regression)
cat(mtcars.model)
## ##################################################
## # [---------Regressions (Direct effects)---------]
## 
## mpg ~ cyl + disp + hp + drat
## disp ~ hp + drat + wt + qsec
# Fit the model with `lavaan`
fit.reg <- sem(mtcars.model, data = mtcars)

# Get regression parameters only
lavaan_reg(fit.reg)
##   Outcome Predictor          SE         Z            p            b
## 1     mpg       cyl  0.69815671 -1.165959 2.436311e-01  -0.81402201
## 2     mpg      disp  0.00901291 -1.541816 1.231184e-01  -0.01389625
## 3     mpg        hp  0.01521110 -1.523275 1.276900e-01  -0.02317068
## 4     mpg      drat  1.52814327  1.409583 1.586627e-01   2.15404553
## 5    disp        hp  0.23487240  1.348926 1.773606e-01   0.31682557
## 6    disp      drat 19.36831070 -2.123660 3.369862e-02 -41.13169751
## 7    disp        wt 14.04152370  5.535006 3.112178e-08  77.71991684
## 8    disp      qsec  6.88881338 -1.874538 6.085630e-02 -12.91334294
##       CI_lower      CI_upper          B  CI_lower_B   CI_upper_B
## 1  -2.18238402   0.554339998 -0.2419101 -0.64651698  0.162696788
## 2  -0.03156123   0.003768732 -0.2865893 -0.64840670  0.075228183
## 3  -0.05298388   0.006642523 -0.2643524 -0.60156925  0.072864499
## 4  -0.84106024   5.149151295  0.1916475 -0.07287256  0.456167633
## 5  -0.14351587   0.777167015  0.1752679 -0.07855326  0.429088994
## 6 -79.09288894  -3.170506091 -0.1774445 -0.33986967 -0.015019402
## 7  50.19903609 105.240797584  0.6135746  0.40870132  0.818447825
## 8 -26.41516906   0.588483178 -0.1861841 -0.37961141  0.007243262
# We can get it prettier with the `rempsyc::nice_table` integration
lavaan_reg(fit.reg, nice_table = TRUE, highlight = TRUE)

Outcome

Predictor

SE

Z

p

b

95% CI (b)

b*

95% CI (b*)

mpg

cyl

0.70

-1.17

.244

-0.81

[-2.18, 0.55]

-0.24

[-0.65, 0.16]

mpg

disp

0.01

-1.54

.123

-0.01

[-0.03, 0.00]

-0.29

[-0.65, 0.08]

mpg

hp

0.02

-1.52

.128

-0.02

[-0.05, 0.01]

-0.26

[-0.60, 0.07]

mpg

drat

1.53

1.41

.159

2.15

[-0.84, 5.15]

0.19

[-0.07, 0.46]

disp

hp

0.23

1.35

.177

0.32

[-0.14, 0.78]

0.18

[-0.08, 0.43]

disp

drat

19.37

-2.12

.034*

-41.13

[-79.09, -3.17]

-0.18

[-0.34, -0.02]

disp

wt

14.04

5.54

< .001***

77.72

[50.20, 105.24]

0.61

[0.41, 0.82]

disp

qsec

6.89

-1.87

.061

-12.91

[-26.42, 0.59]

-0.19

[-0.38, 0.01]