yrosseel / lavaan

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

lavaan dumps estimating a path model but sem does OK #277

Closed erigdon closed 1 year ago

erigdon commented 1 year ago

Michael Filsecker shared this code, more or less, on gmail. It is a simple path model. The sem() function runs fine, but the lavaan() function reports estimation failed and does a dump that I've never seen before, Here is the code:

library(lavaan) lower <- ' 0.42 0.27 0.63 0.24 0.39 0.56 0.03 0.23 0.46 0.48 -0.19 -0.15 -0.20 -0.14 0.13 -0.21 -0.22 -0.40 -0.35 -0.50 0.29 0.04 0.16 0.37 0.31 0.70 0.21 -0.39 0.28 -0.26 -0.41 -0.36 -0.43 0.33 0.71 -0.34'

meece <- getCov(lower, diagonal = FALSE)

model1<-'V8~V3+V5+V6 V5~V3+V4 V6~V3+V4+V5 ' fit1<-lavaan(model1, sample.cov = meece, sample.nobs=256)

fit2<-sem(model1, sample.cov = meece, sample.nobs=256) summary(fit2)

sfcheung commented 1 year ago

On second thought (after I sent this post), I incline to think that this is indeed a bug, as @erigdon wrote:

https://github.com/yrosseel/lavaan/blob/7950cf28dafbf8fadf38e8d96595de8bced3b41c/R/lav_model_estimate.R#L429-L431

I believe line 430 is supposed to be run only if debug = TRUE, as in line 429. Or maybe only one of them is needed, e.g., lines 429-430 should be something like this:

if(debug) print(Sigma.hat[[g]][,]) 

With if(debug), Sigma.hat will not be printed unless debug = TRUE.

yrosseel commented 1 year ago

The problem of the OP was just the use of lavaan() instead of sem(). When the lavaan() function is used, ALL free parameters must be specified in the model syntax, or auto.* arguments should be used to add them. In this case, auto.var = TRUE would do the trick.

I do agree with Shu Fai that lines 429/430 need correction. I decided that (the non-pd) Sigma should only be printed if debug = TRUE, but I changed the stop() into a warning(), because the latter gets printed, while the first one is not printed, due to a try() handler.