yrosseel / lavaan

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

lavInspect(fit, "gamma") returns error for ML-SEMs #327

Open TDJorgensen opened 3 months ago

TDJorgensen commented 3 months ago

I'm trying to get an idea about the required structure of @SampleStats@NACOV for a multilevel SEM, related to the lavaan.mi package. The unstructured model's NACOV is generally stored in a list, but I am unsure whether the list should be length(ngroups) or length(nblocks). The vcov() for a multigroup SEM is a single matrix because parameters can be constrained across groups, but in the unstructured h1 model, the group blocks of that matrix are independent (thus, separate in the NACOV list). I expect same would hold for multilevel SEMs (the level-specific covariance-matrix components are independent), but maybe there is additional complexity.

To see how lavaan provides it, I tried:

example(Demo.twolevel)
lavInspect(fit, "gamma")

Which returned an error from lav_object_inspect_sampstat_gamma():

Error in dimnames(x) <- dn : 
  length of 'dimnames' [1] not equal to array extent

When lav_object_inspect_sampstat_gamma() runs lav_object_gamma(), it yields a single list but with a 42x42 matrix, which I did not expect. In a simpler model without exogenous covariates:

model <- '
    level: 1
        fw =~ y1 + y2 + y3
    level: 2
        fb =~ y1 + y2 + y3
'
fit2 <- sem(model, data = Demo.twolevel, cluster = "cluster")
lavaan:::lav_object_gamma(fit2)

The matrix is only 9x9, when I would expect 6 (co)variances per level + 3 means at Level 2 (so 15, or 18 if 3 means are included at Level 1). I think this is leading to the error when lav_object_inspect_sampstat_gamma() tries to assign names.

TDJorgensen commented 3 months ago

for a multilevel SEM, related to the lavaan.mi package

Specifically, the NACOV would be needed for lavResiduals(). But I notice that lavResiduals(fit2, summary = TRUE) is not available. So perhaps the reason is related to the structure of Gamma not being as obvious as I expect.

yrosseel commented 2 months ago

A partial explanation: