Learn R Programming

⚠️There's a newer version (1.2) of this package.Take me there.

MplusAutomation

The MplusAutomation package leverages the flexibility of the R language to automate latent variable model estimation and interpretation using Mplus, a powerful latent variable modeling program developed by Muthén and Muthén (www.statmodel.com). Specifically, MplusAutomation provides routines for creating related groups of models, running batches of models, and extracting and tabulating model parameters and fit statistics.

Installation

You can install the latest release of MplusAutomation directly from CRAN by running

install.packages("MplusAutomation")

Alternately, if you want to try out the latest development MplusAutomation code, you can install it straight from github using Hadley Wickham's devtools package. If you do not have devtools installed, first install it and then install MplusAutomation.

#install.packages("devtools")
library(devtools)

install_github("michaelhallquist/MplusAutomation")

Questions

For questions, answers, and updates on the status of the MplusAutomation package, email or subscribe to the Google group list.

Examples

You can find a detailed example of how to use the MplusAutomation package in the vignette .

Here is an example of using the package to run a simple path model using the mtcars dataset built into R.

library(MplusAutomation)

pathmodel <- mplusObject(
   TITLE = "MplusAutomation Example - Path Model;",
   MODEL = "
     mpg ON hp;
     wt ON disp;",
   OUTPUT = "CINTERVAL;",
   rdata = mtcars)

## R variables selected automatically as any variable name that occurs in the MODEL, VARIABLE, or DEFINE section.
## If any issues, suggest explicitly specifying USEVARIABLES.
## A starting point may be:
## USEVARIABLES = mpg disp hp wt;

fit <- mplusModeler(pathmodel, modelout = "model1.inp", run = 1L)

That is all it takes to run Mplus! MplusAutomation takes care of figuring out which variables from your R dataset are used in the model and which are not (if it get's confused, you can also specify usevariables). It creates a dataset suitable for Mplus, calls Mplus to run the model on the dataset, and reads it back into R.

There is even pretty printing now. To see the results:

library(texreg)
screenreg(fit, summaries = c("Observations", "CFI", "SRMR"), single.row=TRUE)

The fit is not great, to add some extra paths we can update the model.

pathmodel2 <- update(pathmodel, MODEL = ~ . + "
    mpg ON disp;
    wt ON hp;")

fit2 <- mplusModeler(pathmodel2, modelout = "model2.inp", run = 1L)

We can make some pretty output of both models:

screenreg(list(
  extract(fit, summaries = c("Observations", "CFI", "SRMR")),
  extract(fit2, summaries = c("Observations", "CFI", "SRMR"))),
  single.row=TRUE)

If you want confidence intervals, those can also be printed, so long as they were requested as part of the output (we did in the initial model, which propogates to later models that were updated()ed based on the original model):

screenreg(list(
  extract(fit, cis=TRUE, summaries = c("Observations", "CFI", "SRMR")),
  extract(fit2, cis=TRUE, summaries = c("Observations", "CFI", "SRMR"))),
  single.row=TRUE)

How to Help

If you have a tutorial or examples using MplusAutomation, please add them to the github Wiki.

In addition, on the Wiki, is a list of publications that cite or use MplusAutomation. If you use MplusAutomation in your own work --- papers, posters, presentations, etc. --- please add a citation to the list, and if possible, include an abstract or link to the full text. This helps us get to know our users and how MplusAutomation is being used.

Finally, if you find bugs or have suggestions for new features or ways to enhance MplusAutomation, please let us know! Just click the 'Issues' button at the top of the github page or go here and open a New Issue.

Lastly, if you use MplusAutomation and have space, we greatly appreciating citations. In addition to being easier to track, the recognition and credit help make it easier for us to continue putting our time into developing and sharing this software!

Copy Link

Version

Install

install.packages('MplusAutomation')

Monthly Downloads

8,153

Version

0.8

License

LGPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

Michael Hallquist

Last Published

October 14th, 2020

Functions in MplusAutomation (0.8)

classifyTags

Classifies Tags
SummaryTable

Create a summary table of Mplus model statistics
cd

Change directory
addHeaderToSavedata

Add header to saved data
connectNodes

Connect two nodes
confint.mplus.model

Return confidence intervals for an mplus.model object
extractFreeFile

Extract free file output
extractIndirect

Extract Indirect Effects output
coef.mplus.model

Return coefficients for an mplus.model object
compareModels

Compare the output of two Mplus models
detectColumnNames

Detect Column Names
extractResiduals

Extract residual matrices
detectVariables

Automatically detect variables from an Mplus model object
.mplusMultinomial

Internal Function for Multinomial Regression in Mplus
evaluateConditional

Evaluate Conditional
divideIntoFields

Divide text into fields
.convertData

Convert a matrix or data frame to numeric or integer for Mplus
MplusAutomation

Automating Mplus Model Estimation and Interpretation
extractModelSummaries

Extract summary statistics from a single output file or from a group of Mplus models within a directory
extractParameters_1chunk

Extract Parameters for One Chunk
extractResiduals_1section

Helper subfunction to extract one section of OUTPUT: RESIDUALS Can be called multiple times, as in the case of invariance testing
finalizeInitCollection

Finalize Init Collection
extractTech10

Extract Technical 10 matrix from Mplus
extractTech3

Extract Technical 3 matrix from Mplus
extractWarningsErrors_1file

Extract warnings and errors from 1 mplus file
extractModIndices

Extract model modification indices.
extractTech1

Extract Technical 1 matrix from Mplus
extractModIndices_1chunk

Extract Modification Indices for One Chunk (Section)
extractTech4

Extract Technical 4 matrix from Mplus
get_efa_nfactors

Small helper function to obtain number of factors for an EFA output section
graphModel

Create a graphic model from Mplus
mplus.traceplot

Plot the samples for each MCMC chain as a function of iterations
mixtureSummaryTable

Create a summary table of Mplus mixture models
extractTech7

Extract Technical 7 from Mplus
l_getSavedata_Fileinfo

local function that does the work of getSaveData_Fileinfo
.cleanHashData

Clean data and calculate the md5 hash
getSavedata_Fileinfo

Read Variable Names, Formats, and Widths from data generated by the SAVEDATA Command
parseMplus

Check Mplus code for missing semicolons or too long lines.
getSection

Get an Output Section
extractEFAparameters

Extract the model parameters from an EFA Mplus model output
l_getSavedata_readRawFile

Internal function to load the draws from the Bayesian model posterior distribution
long2LGMM

Long data to wide latent growth mixture model
parseTags

Parses tags in the body section
mplusModeler

Create, run, and read Mplus models.
createMixtures

Create syntax for a batch of mixture models
extractTech8

Extract Technical 8 from Mplus
mplusObject

Create an Mplus model object
lcademo

Latent Class Analysis Demonstration
plotGrowthMixtures

Plot growth mixture models
separateHyphens

Separate Hyphenated Variable Strings
plot.mplusObject

Plot coefficients for an mplusObject
runModels_Interactive

Run Mplus Models Using Graphical Interface
processConditionalTags

Process Conditional Tags
createModels

Create Mplus Input Files from Template
extractAux

Extract Auxiliary condition means and comparisons.
extractModIndices_1file

Extract Modification Indices for One File
extract

Extract function to make Mplus output work with the texreg package
extractFacScoreStats

Extract Factor Score Statistics
extractSummaries_1plan

Worker function used in extractSummaries_1section
extractModelParameters

Extract model parameters from MODEL RESULTS section.
processInit

Process the Init Section
summary.mplusObject

Summarize an mplusObject
testBParamConstraint

Test inequality-constrained hypothesis for two parameters based on iterations of MCMC chains
extractIndirect_section

Extract Indirect Effects output
trainLGMM

Train a variety of latent growth mixture model
update.mplusObject

Update an Mplus model object
updateCurrentValues

Updates current values
extractSummaries_1section

Extract summary information for one section from Mplus output
testBParamCompoundConstraint

Test inequality-constrained hypothesis for two or more parameters based on iterations of MCMC chains
LatexSummaryTable

Display summary table of Mplus model statistics in separate window
createVarSyntax

Create Mplus syntax for variable names
HTMLSummaryTable

Create an HTML file containing a summary table of Mplus model statistics
createSyntax

Create the Mplus input text for an mplusObject
extractClassCounts

Extract Latent Class Counts
extractInput_1file

Extract and parse Mplus input file
getSavedata_Bparams

Load the draws from the Bayesian model posterior distribution (SAVEDATA BPARAMETERS) command into an R data.frame
extractTech12

Extract Technical 12 from Mplus
extractTech15

Extract Technical 15 from Mplus
extractSummaries_1file

Extract the summaries from one file
extractSampstat

Helper function to extract the sample statistics from Mplus output Depends on OUTPUT: SAMPSTAT
extractValue

Extract values from Mplus output An internal function used by extractSummaries_1file to extract parameters from the output file using regular expressions.
extractDataSummary

Function to extract the SUMMARY OF DATA section from Mplus outputs
getSavedata_Data

Load an analysis dataset from the SAVEDATA command into an R data.frame
extractTech9

Extract Technical 9 matrix from Mplus
friendlyGregexpr

Friendly Regular Expression
extractParameters_1file

Extract Parameters for One File
getMultilineSection

Extract a multiline section from Mplus output
isEmpty

Check whether a useable function argument was provided
l_getSavedata_Bparams

Internal function to load the draws from the Bayesian model posterior distribution
mplusRcov

Create Mplus code for various residual covariance structures.
getOutFileList

Get Output File List
getInitTags

Get Initial Tags
extractParameters_1section

Extract Parameters for One Section
lookupValue

Lookup values
matrixExtract

Reconstruct matrix from multi-line text output
mplus_as.numeric

Convert Mplus Number to Numeric
parseCatOutput

Parse Categorical Output
paramExtract

Extract parameters from a data frame of Mplus estimates
plotLTA

Plot latent transition model
plotMixtureDensities

Create density plots for mixture models
prepareMplusData_Mat

Prepare Mplus Data Matrix
replaceBodyTags

Replace Body Tags
print.MplusRstructure

Print an Mplus Residual Structure object
replaceInitTags

Replace Init Tags
showSummaryTable

Display summary table of Mplus model statistics in separate window
readModels

Read Parameters, Summary Statistics, and Savedata from Mplus Output
lookupSimpleTags

Simple tag lookup
lookupTech1Parameter

Lookup the matrix element for a give parameter number
splitFilePath

Split File and Path into Separate Parts
prepareMplusData

Create tab-delimited file and Mplus input syntax from R data.frame
mplusGLM

Function to fit GLMs in Mplus
trimSpace

Trim White Space
recurseReplace

Recursive replace
rmVarWarnings

Remove variable name length warnings from Mplus output file
runModels

Run Mplus Models
mplusAvailable

Check whether Mplus can be found
subsetModelList

Subset a list of Mplus model results
plotMixtures

Create latent profile plots
unlabeledMatrixExtract

Reconstruct matrix from unlabeled multi-line text output
splitDFByRow

Split a data frame into a list by rows
clipString

Clip String
addNode

Add a node to a GRAPHVIZ model