yrosseel / lavaan

an R package for structural equation modeling and more
http://lavaan.org
412 stars 99 forks source link

Error in which(scaledList)[[1]] : subscript out of bounds when running RSA package compare line #345

Closed joshua-zh closed 1 month ago

joshua-zh commented 1 month ago

when I ran the RSA example which called the lavaan, I got the error. I have updated to the latest version of lavaan. However, after degrading the lavaan, the error disappeared,

yrosseel commented 1 month ago

The quick solution is to use r1 <- RSA(z.sq~x*y, df, estimator = "ML") (the default estimator is MLR).

To replicate this outside RSA:

library(lavaan)

# data
set.seed(0xBEEF)
n <- 300
err <- 15 
x <- rnorm(n, 0, 5) 
y <- rnorm(n, 0, 5) 
df <- data.frame(x, y) 
df <- within(df, {
        diff <- x-y
        absdiff <- abs(x-y)
        SD <- (x-y)^2
        z.diff <- diff + rnorm(n, 0, err)
        z.abs <- absdiff + rnorm(n, 0, err)
        z.sq <- SD + rnorm(n, 0, err)
        z.add <- diff + 0.4*x + rnorm(n, 0, err)
        z.complex <- 0.4*x + - 0.2*x*y + + 0.1*x^2 - 0.03*y^2 + rnorm(n, 0, err)
}) 
df$z.binary <- as.numeric(df$z.sq < median(df$z.sq))
df$x2  <- df$x * df$x
df$y2  <- df$y * df$y
df$x_y <- df$x * df$y

fit <- sem('z.sq ~ b1*x + b2*y + b3*x2 + b4*x_y + b5*y2',
           data = df, meanstructure = TRUE, se = "robust.sem",
           test = "yuan.bentler.mplus")

m.IA <- '
z.sq ~ b1*x + b2*y + b3*x2 + b4*x_y + b5*y2

b3==0
b5==0
'

fit2 <- sem(model = m.IA, data = df, meanstructure = TRUE, se = "robust.sem",
            test = "yuan.bentler.mplus")
lavTestLRT(fit, fit2)

This fails because the robust test statistic is NA (because tr(UG) is negative). And although the error message was difference, this also failed in lavaan 0.6-17/16/15. The most elegant solution is probably to produce a warning and fall back to a standard chi-difference test.

joshua-zh commented 1 month ago

Thank you for your inspiring reply. Adding estimator = "ML" makes codes run successfully.