Learn R Programming

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

4,587

Version

1.1.1

License

LGPL-3

Last Published

January 30th, 2024

Functions in MplusAutomation (1.1.1)

cd

Change directory
divideIntoFields

Divide text into fields
createSyntax

Create the Mplus input text for an mplusObject
createVarSyntax

Create Mplus syntax for variable names
LatexSummaryTable

Display summary table of Mplus model statistics in separate window
detectVariables

Automatically detect variables from an Mplus model object
createMixtures

Create syntax for a batch of mixture models
clipString

Clip String
extractModelParameters

Extract model parameters from MODEL RESULTS section.
extractModelSummaries

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

Extract Parameters for One Section
extractResiduals

Extract residual matrices
coef.mplus.model

Return coefficients for an mplus.model object
createModels

Create Mplus Input Files from Template
extractDataSummary

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

Extract Technical 15 from Mplus
compareModels

Compare the output of two Mplus models
extractTech3

Extract Technical 3 matrix from Mplus
detectColumnNames

Detect Column Names
MplusAutomation

Automating Mplus Model Estimation and Interpretation
getSavedata_Fileinfo

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

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

Clean data and calculate the md5 hash
plotGrowthMixtures

Plot growth mixture models
evaluateConditional

Evaluate Conditional
extractModIndices_1chunk

Extract Modification Indices for One Chunk (Section)
extractEFAparameters

Extract the model parameters from an EFA Mplus model output
extractModIndices_1file

Extract Modification Indices for One File
extractIndirect

Extract Indirect Effects output
extract

Extract function to make Mplus output work with the texreg package
.convertData

Convert a matrix or data frame to numeric or integer for Mplus
confint.mplus.model

Return confidence intervals for an mplus.model object
plotLTA

Plot latent transition model
processInit

Process the Init Section
readModels

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

Extract Indirect Effects output
extractParameters_1chunk

Extract Parameters for One Chunk
extractParameters_1file

Extract Parameters for One File
.mplusMultinomial

Internal Function for Multinomial Regression in Mplus
detectMplus

Detect the location/name of the Mplus command
extractResiduals_1section

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

Extract Factor Score Statistics
extractAux

Extract Auxiliary condition means and comparisons.
extractClassCounts

Extract Latent Class Counts
extractInput_1file

Extract and parse Mplus input file
extractTech10

Extract Technical 10 matrix from Mplus
extractModIndices

Extract model modification indices.
extractTech8

Extract Technical 8 from Mplus
extractTech12

Extract Technical 12 from Mplus
finalizeInitCollection

Finalize Init Collection
htmlout

Read in Mplus Output File from HTML on the Mplus Website
friendlyGregexpr

Friendly Regular Expression
extractSampstat

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

Check whether a useable function argument was provided
mplusObject

Create an Mplus model object
mplusRcov

Create Mplus code for various residual covariance structures.
extractValue

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

Extract Technical 9 matrix from Mplus
replaceInitTags

Replace Init Tags
getSection

Get an Output Section
rmVarWarnings

Remove variable name length warnings from Mplus output file
l_getSavedata_Bparams

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

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

Connect two nodes
separateHyphens

Separate Hyphenated Variable Strings
getSavedata_Bparams

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

Extract the summaries from one file
extractSummaries_1plan

Worker function used in extractSummaries_1section
l_getSavedata_Fileinfo

local function that does the work of getSaveData_Fileinfo
getOutFileList

Get Output File List
long2LGMM

Long data to wide latent growth mixture model
extractFreeFile

Extract free file output
showSummaryTable

Display summary table of Mplus model statistics in separate window
getInitTags

Get Initial Tags
extractWarningsErrors_1file

Extract warnings and errors from 1 mplus file
getMultilineSection

Extract a multiline section from Mplus output
updateCurrentValues

Updates current values
get_results

Extract Mplus results
graphModel

Create a graphic model from Mplus
mplusGLM

Function to fit GLMs in Mplus
subsetModelList

Subset a list of Mplus model results
extractSummaries_1section

Extract summary information for one section from Mplus output
extractTech1

Extract Technical 1 matrix from Mplus
summary.mplusObject

Summarize an mplusObject
lookupSimpleTags

Simple tag lookup
mplusAvailable

Check whether Mplus can be found
mplus.traceplot

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

Create, run, and read Mplus models.
mplus_as.numeric

Convert Mplus Number to Numeric
paramExtract

Extract parameters from a data frame of Mplus estimates
plotMixtureDensities

Create density plots for mixture models
extractTech4

Extract Technical 4 matrix from Mplus
recurseReplace

Recursive replace
replaceBodyTags

Replace Body Tags
runModels

Run Mplus Models
runModels_Interactive

Run Mplus Models Using Graphical Interface
matrixExtract

Reconstruct matrix from multi-line text output
plotMixtures

Create latent profile plots
extractTech7

Extract Technical 7 from Mplus
lcademo

Latent Class Analysis Demonstration
l_getSavedata_readRawFile

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

Lookup values
parseCatOutput

Parse Categorical Output
lookupTech1Parameter

Lookup the matrix element for a give parameter number
mixtureSummaryTable

Create a summary table of Mplus mixture models
splitFilePath

Split File and Path into Separate Parts
splitDFByRow

Split a data frame into a list by rows
trainLGMM

Train a variety of latent growth mixture model
trimSpace

Trim White Space
print.MplusRstructure

Print an Mplus Residual Structure object
parseMplus

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

Process Conditional Tags
parseTags

Parses tags in the body section
plot.mplusObject

Plot coefficients for an mplusObject
unlabeledMatrixExtract

Reconstruct matrix from unlabeled multi-line text output
update.mplusObject

Update an Mplus model object
prepareMplusData_Mat

Prepare Mplus Data Matrix
testBParamConstraint

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

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

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

Classifies Tags
SummaryTable

Create a summary table of Mplus model statistics
HTMLSummaryTable

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

Add a node to a GRAPHVIZ model
OS

Functions to identify the operating system