我正在估计一个已观察到变量的 SEM 模型。我正在使用 SEM 来使用 FIML 处理缺失数据。我的模型有一个交互项来测试适度性。这是一个说明问题的玩具示例。
library(lavaan)
library(car)
library(dplyr)
data(starwars)
sw2 <- starwars %>% mutate(
male = Recode(sex, "'male' = 1; NA=NA; else = 0"),
human = Recode(species, "'Human' = 1; NA=NA; else = 0"),
maleXby = male * birth_year,
)
mod <- 'mass ~ height + human + male + birth_year + maleXby'
fit <- sem(mod, data = sw2, missing="fiml.x")
summary(fit)
我想要做的是像边缘图一样绘制交互项,以可视化交互效果。但是像库(交互)这样的包不适用于
lavaan
类的对象。我怎样才能想象这个?有没有一个包(比如interactions
)可以让这变得更容易。
您可以使用
lm()
拟合此模型,但我认为您希望能够使用 FIML 估计,是吗? 在这种情况下,您可以使用 emmeans
包,如果您加载了 lavaan
包,它可以在 semTools
类对象上工作。
您没有说哪个预测变量是焦点变量还是调节变量,但我假设您希望将
male
视为调节变量,因为它是一个分组变量。 下面的示例可以通过切换它们在 pairs()
功能中的角色,以及选择不同的 birth_year
级别 at=
来探测 male
的效果来进行调整。 当 birth_year
是焦点预测变量时,无论选择哪个级别,其线性效果都是相同的,所以我选择了下面完整的 range()
。
library(emmeans)
library(semTools)
## for ease of use, fit model using colon operator
mod <- 'mass ~ height + human + male + birth_year + male:birth_year'
fit <- sem(mod, data = sw2, missing = "fiml.x")
## calculate expected marginal means for multiple
## levels of male (1:0) and birth_year
BYrange <- range(sw2$birth_year, na.rm = TRUE)
em.mass <- emmeans(fit, specs = ~ birth_year | male,
at = list(male = 1:0, birth_year = BYrange),
# because SEMs can have multiple DVs:
lavaan.DV = "mass")
em.mass
## probe effect of year across sex
rbind(pairs(em.mass))
## plot effect of year across sex
emmip(em.mass, male ~ birth_year) # 2 lines in same plot
emmip(em.mass, ~ birth_year | male) # in separate panels
我正在尝试这个,但目前似乎不起作用。
p_load(lavaan, jtools, emmeans, semTools)
data <- center(
data = data,
vars = c("y1comm", "y1alumm"),
)
data$INT <- data$y1comm * data$y1sgvmd
model_lavaan <- sem("y3alumm ~ INT + y1sgvmd + y1comm + assign + y1sgdc2 + y0orimon + y1alumm", data = data, estimator = "MLR", missing = "fiml", fixed.x = F)
> BYrange <- range(data$y1comm, na.rm = TRUE)
> em.mass <- emmeans(model_lavaan, specs = ~ y1comm | y1sgvmd,
+ at = list(y1comm = BYrange, y1sgvmd = 1:0),
+ # because SEMs can have multiple DVs:
+ lavaan.DV = "y3alumm")
Error in EETA[, ov.x.dummy.lv.idx] <- eXo : replacement has length zero
Error in (function (object, at, cov.reduce = mean, cov.keep = get_emm_option("cov.keep"), :
Perhaps a 'data' or 'params' argument is needed