Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • New package dwlsmv, WLSMV estimation of SEM/CFA for binary and ordinal indicators in Stata

    I am excited to share a new Stata package, dwlsmv, which implements weighted least squares mean- and variance-adjusted (WLSMV) estimation for binary and ordinal indicators. It fits single- and multiple-group confirmatory factor and structural equation models, and exploratory factor models with oblique geomin rotation.

    The test statistic is the scaled-and-shifted (T3) mean- and variance-adjusted chi-square, the correction Mplus has used for WLSMV since version 6 (Asparouhov and Muthén, 2010). The "d" stands for the diagonal weight matrix used in estimation; the full asymptotic covariance matrix is still used for the robust standard errors and the test statistic (Muthén, du Toit, and Spisic, 1997).

    The current release is v0.3.0. Stata 16 is the floor, and it has been tested on Stata 16.1, 18 and 19 on Windows (macOS and Linux are not yet tested). This is a Mata implementation and should work across platforms.

    Installation:
    Code:
    net install dwlsmv, from("https://raw.githubusercontent.com/bbachilles/dwlsmv/v0.3.0/dist/")
    net get dwlsmv // example data
    help dwlsmv
    Source, specification and derivations are available at https://github.com/bbachilles/dwlsmv. The code is licensed under GPL-3.0-or-later; the specification, derivations and documentation under CC BY 4.0.

    This was built in close collaboration with and using Claude Code (code generated by Opus) with ChatGPT utilized as an independent sounding board in highly technical decision making (see follow-up post).

    What v0.3.0 supports
    • Single- and multiple-group factor models with binary and ordinal indicators, including regression paths between latent variables. Missing data are handled by listwise deletion.
    • Cross-sectional measurement invariance (configural, thresholds, metric, scalar) following the Wu and Estabrook (2016) parameterization, using group() with metric(unitvariance). One deliberate restriction: invariance testing is not yet supported for factors measured only by binary indicators. Beyond metric invariance their identification is unresolved, so dwlsmv refuses these models rather than fitting them.
    • Nested model comparison with the included difftest command: a mean- and variance-adjusted chi-square difference test (Asparouhov and Muthén, 2006) for single-group models and for nested invariance levels across groups. difftest checks that the models are nested and refuses the comparison when they are not, including models nested only through a reparameterization.
    • EFA with oblique geomin rotated loadings and factor correlations (point estimates only).
    • Fit indices: CFI, TLI and RMSEA, with changes in CFI and RMSEA between invariance levels.v0.3.0 necessarily has some limitations in its capability.
    Syntax follows Stata's sem path notation, so it should feel familiar to sem users:
    Code:
    use dwlsmv_example, clear
    dwlsmv (F1 -> y1 y2 y3) (F2 -> y4 y5 y6) (F2 <- F1) // first loading of each factor fixed to 1
    dwlsmv (F1 -> y1 y2 y3) (F2 -> y4 y5 y6) (F2 <- F1), metric(unitvariance) // factor variances fixed to 1
    dwlsmv (F1 F2 -> y1-y6), efa(F1 F2) // EFA, oblique geomin
    dwlsmv is actively being developed and contributors are welcome! Planned development aims to address these:
    • Geomin rotated standard errors in EFA
    • Observed covariates that are not part of measurement models. These require implementation of polyserial correlations, which was out of scope for v0.3.0.
    • Unlimited parameter constraints. Currently only loading constraints for identifying the marker of a factor and those related to measurement invariance are supported,
    • Second order or hierarchical factor structures, including latent "curve of factors" models.
    • vce options, focused on vce(cluster clusterid)
    • Exploratory structural equation modeling (ESEM)
    Feedback, bug reports and feature requests are welcome here or as GitHub issues (https://github.com/bbachilles/dwlsmv/issues). The README includes citation information.

    References
    Asparouhov, T., and B. Muthén. 2006. Robust chi square difference testing with mean and variance adjusted test statistics. Mplus Web Notes No. 10.
    Asparouhov, T., and B. Muthén. 2010. Simple second order chi-square correction. Technical appendix, Mplus.
    Muthén, B., S. H. C. du Toit, and D. Spisic. 1997. Robust inference using weighted least squares and quadratic estimating equations in latent variable modeling with categorical and continuous outcomes. Unpublished manuscript.
    Wu, H., and R. Estabrook. 2016. Identification of confirmatory factor analysis models of different levels of invariance for ordered categorical outcomes. Psychometrika 81: 1014–1045.

  • #2
    Technical follow-up, for those interested in the development details.

    How it was validated
    The project has four parts:
    • Derivation: the mathematics (Stage 1 influence functions, the asymptotic covariance matrix Gamma, the Jacobian Delta, the T3 statistic, the rank criteria and the invariance parameterization), with executable verification in R. See spec/derivations on GitHub.
    • Implementation: Mata modules implementing the derived estimator and its numerical safeguards behind a fixed internal API.
    • Validation: tiered reference results (base R, lavaan, Mplus), Monte Carlo checks, and runs on the Stata 16 floor.
    • Interface: sem's path syntax.
    An important principle was separating two kinds of tolerance. Validation tolerances decide whether results agree with independent references (base R, lavaan, Mplus) and are never loosened to make a comparison pass. Algorithmic tolerances are part of the estimator itself: they govern when a root-finder stops and which numerical results are accepted, and they are fixed by the specification rather than tuned.

    The estimator's statistical properties (parameter recovery, standard error performance and the empirical size of the T3 test) are evaluated separately from numerical agreement, using population fixtures and Monte Carlo experiments, with Monte Carlo standard errors quantifying simulation uncertainty.

    AI-assisted development
    dwlsmv was built with Claude Code (primarily Anthropic's Opus models) as the principal development tool, with ChatGPT as an independent sounding board for highly technical decisions. I, as the developer with domain expertise, retained responsibility for the specification, methodological decisions, validation criteria and the final product. The workflow combined iterative specification, code generation, testing, adversarial review and refinement.

    In Cory Doctorow's terms, this is a "centaur" project: I used an LLM as a tool to build something I was personally interested in and believe will be valuable to Stata users. I developed it on my own time, at my own pace, and with considerable personal investment in getting the statistical methodology and numerical implementation right. For background on Doctorow's thesis: https://locusmag.com/feature/comment...erse-centaurs/

    Comment


    • #3
      Hi Erik Ruzek. Thank you for sharing -dwlsmv-. I'm exploring PLS-SEM now, there's some fun in learning structure equation model. A very good website providing materials here: SEM Example 07 - Comparing ML and WLSMV Estimators for Ordinal, Likert-Type Items: Demonstrations with the Health Behaviour in School-Aged Children Dataset

      Comment


      • #4
        Completely off-topic but I always try to make my command names pronounceable or even -- contrary to StataCorp advice -- use standard English words.

        dwlsmv has meaning as an abbreviation -- but no vowels either.

        Comment


        • #5
          I see value in your approach to naming, Nick. I didn't think about the lack of vowels!

          Comment


          • #6
            Thanks for this, Erik Ruzek. I don't often (or ever?) use these kinds of models myself, but some of the students I teach may find this package very useful. 👍

            I have one small suggestion about the help file. I noticed that it does not currently have any of the following sections (which many authors include at the end of the file):
            • Author
            • Acknowledgments
            • References
            • Also see
            Cheers,
            Bruce
            --
            Bruce Weaver
            Email: [email protected]
            Version: Stata/MP 19.5 (Windows)
            Crypticity belongs in crosswords, not code! 🤨

            Comment


            • #7
              Good news! An updated dwlsmv, 0.4.1*, is available at https://github.com/bbachilles/dwlsmv.

              Since 0.3.0, dwlsmv allows one binary covariate, coded 0/1, as a predictor of a latent factor, (F <- x), and/or with a direct effect on an indicator, (y5 <- x). The model is fitted conditional on x: x’s distribution is taken as given and is not part of the model-implied moments; the factor and the indicators’ latent responses are regressed on x. The thresholds are those of the group coded 0, and the slope on F is the difference in factor means between the groups. A covariate not coded 0/1, a second covariate, or a covariate combined with group() is refused with an error.
              Code:
              * Install or update
              net install dwlsmv, from(“https://raw.githubusercontent.com/bbachilles/dwlsmv/v0.4.1/dist/”) replace
              
              * Get and load the two-group example data
              net get dwlsmv, from(“https://raw.githubusercontent.com/bbachilles/dwlsmv/v0.4.1/dist/”)
              use dwlsmv_example_mg.dta, clear
              generate byte group = grp - 1
              
              *Regress the factor on group, with a direct effect of group on y5
              dwlsmv (F -> y1-y5) (F <- group) (y5 <- group)
              Why a conditional model when a multiple-group model is available? A multiple-group model compares populations and lets loadings, thresholds and variances differ, which is what measurement invariance testing needs. The conditional model holds the loadings, the factor’s variance and the residual structure equal across x; only the factor mean shifts, plus the thresholds of any item given a direct linear effect of x. That makes it more parsimonious, and it extends to predictors without turning each combination into a separate group. A direct effect such as (y5 <- group) is then a check of threshold invariance for that item. For an important predictor such as treatment, researchers often test invariance with a multiple-group model first, then move to the structural model.

              Thanks to the suggestion of Bruce Weaver, the help files for both dwlsmv and difftest have been updated with author, acknowledgements, references, and also see.

              *0.4.1 fixes the help files’ display; the covariate arrived in 0.4.0.
              Last edited by Erik Ruzek; 16 Nov 2026, 09:06. Reason: Rephrasing of description of conditional model

              Comment


              • #8
                Hi Erik Ruzek. First, thanks for tweaking the help files. Second, I had to shorten some lines in the code you posted (via ///) to get them to run. Third, I (think I) had to add a replace option to the net get command (presumably because I had executed it previously). Fourth, the -dwlsmv- command is generating an error. as shown below.


                Code:
                . * Install or update
                . net install dwlsmv, ///
                > from("https://raw.githubusercontent.com/bbachilles/dwlsmv/v0.4.1/dist/") ///
                > replace
                checking dwlsmv consistency and verifying not already installed...
                all files already exist and are up to date.
                
                . 
                . * Get and load the two-group example data
                . net get dwlsmv, from ///
                > ("https://raw.githubusercontent.com/bbachilles/dwlsmv/v0.4.1/dist/") replace
                checking dwlsmv consistency and verifying not already installed...
                all files already exist and are up to date.
                
                . use dwlsmv_example_mg.dta, clear
                (dwlsmv invariance example: 5 ordinal items, 1 factor, 2 groups (simulated))
                
                . generate byte group = grp - 1
                
                . 
                . *Regress the factor on group, with a direct effect of group on y5
                . dwlsmv (F -> y1-y5) (F <- group) (y5 <- group)
                dwlsmv: observed exogenous variables (group) are not supported: dwlsmv fits latent factors measured by ordinal indicators.
                r(198);
                
                end of do-file
                
                r(198);
                Cheers,
                Bruce


                --
                Bruce Weaver
                Email: [email protected]
                Version: Stata/MP 19.5 (Windows)
                Crypticity belongs in crosswords, not code! 🤨

                Comment


                • #9
                  Erik Ruzek replied to me off-list and suggested that I try the following:
                  Code:
                  * Reinstall dwlsmv again
                  net install dwlsmv, from("https://raw.githubusercontent.com/bbachilles/dwlsmv/v0.4.1/dist/") replace
                  
                  * Restart Stata.
                  
                  * Check version number for dwlsmv
                  which dwlsmv
                  * Check for any older versions
                  ado dir
                  * if you have an older dwlsmv listed as say #45 on ado dir, uninstall it
                  ado uninstall [45]
                  It turned out that an older version of -dwlsmv- was still lurking. After I uninstalled it, Erik's code in #7 ran without incident.

                  Cheers,
                  Bruce
                  Last edited by Bruce Weaver; 16 Nov 2026, 15:35. Reason: Crossed with #10.
                  --
                  Bruce Weaver
                  Email: [email protected]
                  Version: Stata/MP 19.5 (Windows)
                  Crypticity belongs in crosswords, not code! 🤨

                  Comment


                  • #10
                    After with chatting with Bruce privately, we resolved the issue. If you installed a previous version of dwlsmv, you may have conflicting dwlsmv ados and Stata is using the prior install when you call dwlsmv. You can see if that is the case with a quick search:
                    Code:
                    which dwlsmv, all
                    If you see multiple versions, it's probably worth uninstalling the earlier version:
                    Code:
                    ado dir
                    # if you have an older dwlsmv listed as say #45 on ado dir, uninstall it
                    ado uninstall [45]
                    Restart Stata just to be safe and then re-install dwlsmv:
                    Code:
                    net install dwlsmv, from(“https://raw.githubusercontent.com/bbachilles/dwlsmv/v0.4.1/dist/”) replace

                    Comment


                    • #11
                      This is something that should have been officially supported for years now in my opinion! Thanks for putting this out there.

                      Comment


                      • #12
                        Originally posted by Erik Reinbergs View Post
                        This is something that should have been officially supported for years now in my opinion! Thanks for putting this out there.
                        I rembers that Professor Richard Williams in wishlist suggested that Stata to buy Mplus, and someone suggestd to have a R integration. Whether Mplus style or lavaan style, I think (hope) that will be more and more official and user-written SEM family command in Stata. By the way, take a time to compare -polysem- wrote by Yusuf Yusuf. A small piece of episode here.
                        Code:
                        . ssc describe polysem
                        
                        ------------------------------------------------------------------------------------------------
                        package polysem from http://fmwww.bc.edu/repec/bocode/p
                        ------------------------------------------------------------------------------------------------
                        
                        TITLE
                              'POLYSEM': module to perform confirmatory factor analysis of ordinal indicators by
                                diagonally weighted least squares on polychoric correlations
                        
                        DESCRIPTION/AUTHOR(S)
                              
                                   polysem fits the factor model R = Lambda Phi Lambda' + Theta
                              to the polychoric, polyserial and Pearson correlations of the
                              indicators. Here Theta is diagonal with Theta_ii = 1 - (Lambda
                              Phi Lambda')_ii, because the latent responses have unit variance.
                                 The command:  1. runs polycorr to obtain the vector of
                              correlations r and its covariance matrix V;      2. minimizes
                              (r - sigma(theta))' W (r - sigma(theta)) by Gauss-Newton with
                              step halving.
                              
                              KW: confirmatory factor analysis
                              KW: polychoric correlations
                              
                              Requires: Stata version 14 and polycorr from SSC (q.v.)
                              
                              Distribution-Date: 20261030
                              
                              Author:  Yusuf Toyin Yusuf,  Kwara State University
                              Support: email  [email protected]
                              
                        
                        INSTALLATION FILES                              (type net install polysem)
                              polysem.ado
                              polysem.sthlp
                        
                        ANCILLARY FILES                                 (type net get polysem)
                              polysem_examples.do
                              polysem_cert.do
                        ------------------------------------------------------------------------------------------------
                        (type ssc install polysem to install)

                        Comment


                        • #13
                          Great find, Chen! I was not aware of this package. It is very nice. I particularly like its clean display of loadings, which looks more like the output one gets from most non-sem Stata commands. I have been considering some revisions to dwlsmv's output for a while now (they currently mimic sem) and this gives me a good comparison of what is possible. The one thing polysem does not display is item thresholds. Its fit is to the correlation vector only; "thresholds are left unrestricted, so the model has no mean structure" (READ, help). Accordingly, thresholds are not estimated, posted or shown by polysem.
                          Last edited by Erik Ruzek; 17 Nov 2026, 15:22. Reason: Grammatical fix

                          Comment


                          • #14
                            I am happy to share that version 0.5.0 of dwlsmv is now available! This version adds two new features to the package's EFA capabilities.

                            First, rotated standard errors (delta-method) are now available for EFA fits but are not shown by default. You can get them with the option se or if you prefer Wald confidence intervals instead (they tend to be more informative for EFAs), use option ci. You can also get both at once!
                            Code:
                            use dwlsmv_example.dta, clear
                            dwlsmv (F1 F2 -> y1 y2 y3 y4 y5 y6), efa(F1 F2) ci
                            Gives the following output:
                            Code:
                            DWLS estimation, WLSMV test (ordinal indicators)  Number of obs   =      5000
                            Metric: factor variances fixed at 1 (for a factor predicted by other factors, its residual variance)
                            Scaled-and-shifted test (T3):                     chi2(4)         =     3.505
                                                                              Prob > chi2     =    0.4771
                                                                              RMSEA (scaled)  =    0.0000
                                                                              CFI (scaled)    =    1.0000
                                                                              TLI (scaled)    =    1.0003
                            
                            Rotation: geomin, oblique (epsilon = .0001, 30 starts, 30 converged)
                            
                            Rotated loadings (estimate and 95% Wald interval)
                                         |   F1                          F2                      
                            -------------+--------------------------------------------------------
                            y1           |   0.720 [0.673, 0.767]       -0.017 [-0.067, 0.033]    
                            y2           |   0.657 [0.611, 0.703]        0.020 [-0.031, 0.071]    
                            y3           |   0.659 [0.623, 0.694]        0.002 [-0.010, 0.013]    
                            y4           |   0.003 [-0.021, 0.027]       0.712 [0.676, 0.747]    
                            y5           |   0.007 [-0.028, 0.042]       0.700 [0.662, 0.739]    
                            y6           |  -0.012 [-0.054, 0.029]       0.712 [0.671, 0.753]    
                            
                            Factor correlations (estimate and 95% Wald interval)
                                         |   F1                          F2                      
                            -------------+--------------------------------------------------------
                            F1           |   1.000                                                
                            F2           |   0.467 [0.419, 0.515]        1.000
                            After running an EFA, you can now run the screeplot command to get the screeplot.

                            Second, a new subcommand, efacompare, provides summary information about multiple EFAs fit to the same items sequentially.
                            Code:
                            efacompare y1-y6, maxfactors(3)
                            This gives:
                            Code:
                            Exploratory factor analysis by number of factors m (oblique geomin)
                            Observations: 5000.  Items (p = 6): y1 y2 y3 y4 y5 y6
                            Columns are defined in efacompare.
                            
                            Fit
                            --------------------------------------------------------------------
                               m    df  status           T3        p    RMSEA      CFI      TLI
                            --------------------------------------------------------------------
                               1     9  fitted     1301.759    0.000    0.170    0.805    0.674
                               2     4  fitted        3.505    0.477    0.000    1.000    1.000
                               3     0  rot fail          .        .        .        .        .
                            --------------------------------------------------------------------
                            
                            Rotated diagnostics and eigenvalue
                            --------------------------------------------------------------------
                               m  minima         gap      lam3    phimax   comm1       ev_m
                            --------------------------------------------------------------------
                               1       1           .     0.617         .       0      2.638
                               2       1           .     0.657     0.467       0      1.287
                               3       .           .         .         .       .          .
                            --------------------------------------------------------------------
                            Rotation failed (m = 3): the geomin rotation did not converge from any of its starts, and nothing is reported for these
                                  rows. dwlsmv itself suggests fewer factors or more starts with rstarts().
                            Rotated loadings are not shown in the current instantiation of efacompare. Users are encouraged to run a follow-up EFA to see the loadings, as above.

                            Finally, and inspired by polysem, dwlsmv shows results of SEM fits in more compact tables:
                            Code:
                            . dwlsmv (F1 -> y1 y2 y3) (F2 -> y4 y5 y6) (F2 <- F1)
                            DWLS estimation, WLSMV test (ordinal indicators)  Number of obs   =      5000
                            Metric: marker (first-listed indicator)
                            Scaled-and-shifted test (T3):                     chi2(8)         =     5.154
                                                                              Prob > chi2     =    0.7410
                                                                              RMSEA (scaled)  =    0.0000
                                                                              CFI (scaled)    =    1.0000
                                                                              TLI (scaled)    =    1.0008
                            
                                            |   Estimate Std. err.       z   P>|z|    [95% conf. interval]
                            ----------------+-------------------------------------------------------------
                            Loadings on F1  |
                              y1            |          1  (marker)
                              y2            |     0.9665    0.0344   28.06   0.000      0.8990      1.0341
                              y3            |     0.9432    0.0340   27.72   0.000      0.8766      1.0099
                            Loadings on F2  |
                              y4            |          1  (marker)
                              y5            |     0.9896    0.0306   32.36   0.000      0.9297      1.0495
                              y6            |     0.9798    0.0304   32.22   0.000      0.9202      1.0394
                            ----------------+-------------------------------------------------------------
                            Structural      |
                              F2 <- F1      |     0.4772    0.0247   19.35   0.000      0.4289      0.5256
                            ----------------+-------------------------------------------------------------
                            Variances       |
                              var(F1)       |     0.4908    0.0225   21.82   0.000      0.4467      0.5349
                              var(e.F2)     |     0.3993    0.0185   21.58   0.000      0.3630      0.4356
                            ------------------------------------------------------------------------------
                            Thresholds are not shown; the option thresholds shows them (they are in e(b)).
                            Category counts (the fewest observations in any one category):
                                lowest or highest category: 1209 (y3, highest)
                                middle category:            1710 (y5, category 2)
                            Installation/updating is the same as before, except you need to change the version number:
                            Code:
                            net install dwlsmv, from("https://raw.githubusercontent.com/bbachilles/dwlsmv/v0.5.0/dist/") replace
                            Feedback is always appreciated!
                            Last edited by Erik Ruzek; 19 Nov 2026, 09:35. Reason: Note about screeplot after EFA fit

                            Comment


                            • #15
                              Four years ago WLSMV estimation in stata

                              Comment

                              Working...
                              X