The problem in your function is that you refer to MyData
in the last line even though you do not pass this dataset to the function. Actually, the function does look into your global environment and finds MyData
there. But your z-scored variables and Interaktion
are not included in this version of MyData
, so the function reports an error about "missing variables in dataset".
It works with the following changes:
Moderation <- function(Mod, UV, AV) {
require(lavaan) #This ensures the function works even if you did not do library(lavaan) first.
ZMod <- scale(Mod) #I simplified stuff here. The "scale" function is equivalent to what you did.
ZUV <- scale(UV)
Interaktion <- ZUV*ZMod
MyData <- as.data.frame(list(ZMod=ZMod, ZUV=ZUV, AV=AV, Interaktion=Interaktion)) #Here, MyData is generated so that you can use it further below
Moderation.fit <- 'AV ~ ZUV + ZMod + Interaktion' #nothing changed here
summary(sem(model = Moderation.fit, data = MyData, meanstructure = TRUE))
}
I tested it with the popular mtcars
dataset:
data(mtcars)
Moderation(mtcars$am, mtcars$hp, mtcars$mpg)
##lavaan 0.6-7 ended normally after 28 iterations
##
## Estimator ML
## Optimization method NLMINB
## Number of free parameters 5
##
## Number of observations 32
##
##Model Test User Model:
##
## Test statistic 0.000
## Degrees of freedom 0
##
##Parameter Estimates:
##
## Standard errors Standard
## Information Expected
## Information saturated (h1) model Structured
##
##Regressions:
## Estimate Std.Err z-value P(>|z|)
## AV ~
## ZUV -4.043 0.560 -7.225 0.000
## ZMod 2.633 0.513 5.134 0.000
## Interaktion 0.014 0.527 0.026 0.979
##
##Intercepts:
## Estimate Std.Err z-value P(>|z|)
## .AV 20.094 0.505 39.785 0.000
##
##Variances:
## Estimate Std.Err z-value P(>|z|)
## .AV 7.670 1.917 4.000 0.000
Viel Erfolg und Spass damit!
MyData
– coffeinjunky Nov 22 '20 at 16:40ZAV
defined? – YBS Nov 22 '20 at 16:59