## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----setup--------------------------------------------------------------------
library(semboottools)
library(lavaan)

## -----------------------------------------------------------------------------
library(lavaan)
# Simulate data
set.seed(1234)
n <- 200
x <- runif(n) - 0.5
m <- 0.4 * x + rnorm(n)
y <- 0.3 * m + rnorm(n)
dat <- data.frame(x, m, y)

# Specify model
model <- '
  m ~ a * x
  y ~ b * m + cp * x
  ab := a * b
'

# Fit model
fit0 <- sem(model,
            data = dat,
            fixed.x = FALSE)

# Store bootstrap draws using `store_boot()`.
# `R`, the number of bootstrap samples, should be ≥2000 in real studies.
# `parallel` should be used unless fitting the model is fast.
# Set `ncpus` to a larger value or omit it in real studies.
# Before calling `jab_after_boot()`, you **must** re-run the model with store_boot(keep.idx = TRUE).  This is crucial: without `keep.idx = TRUE`, the bootstrap index matrix (boot.idx) will not be saved, and JAB cannot compute leave-one-out subdistributions.

fit2 <- store_boot(
          fit0,
          R = 500,
          ncpus = 2,
          iseed = 2345,
          keep.idx = TRUE,
          parallel = "snow"
        )

## -----------------------------------------------------------------------------
# Run JAB analysis for b
res1 <- semboottools::jab_after_boot(
  fit2,
  param        = "b",
  standardized = TRUE,
  top_k        = 5,
  plot         = TRUE,
  plot_engine  = "ggplot2",
  font_family  = "sans"
)

# Run JAB analysis for ab
res2 <- semboottools::jab_after_boot(
  fit2,
  param        = "ab",
  standardized = TRUE,
  top_k        = 10,
  plot         = TRUE
)

