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

6,626

Version

1.2

License

LGPL-3

Maintainer

Michael Hallquist

Last Published

September 2nd, 2025

Functions in MplusAutomation (1.2)

createSyntax

Create the Mplus input text for an mplusObject
confint.mplus.model

Return confidence intervals for an mplus.model object
createVarSyntax

Create Mplus syntax for variable names
convert_to_filelist

helper function to crawl over the target location, determine if it is a file or folder, then locate all .inp files, and convert them to absolute paths
createModels

Create Mplus Input Files from Template
.mplusMultinomial

Internal Function for Multinomial Regression in Mplus
detectVariables

Automatically detect variables from an Mplus model object
detectColumnNames

Detect Column Names
dhms_to_hours

helper function to convert a dhms string to the number of hours for combining similar job times
evaluateConditional

Evaluate Conditional
compareModels

Compare the output of two Mplus models
clipString

Clip String
detectMplus

Detect the location/name of the Mplus command
expandCmd

Expand Mplus-style hyphenated variable ranges
divideIntoFields

Divide text into fields
.convertData

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

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

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

Extract Auxiliary condition means and comparisons.
extractIndirect

Extract Indirect Effects output
extractClassCounts

Extract Latent Class Counts
extractParameters_1chunk

Extract Parameters for One Chunk
extractFacScoreStats

Extract Factor Score Statistics
extractDataSummary

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

Extract and parse Mplus input file
extractModelParameters

(DEPRECATED) Extract model parameters from MODEL RESULTS section.
extractModIndices_1chunk

Extract Modification Indices for One Chunk (Section)
extractParameters_1section

Extract Parameters for One Section
extractIndirect_section

Extract Indirect Effects output
extractModIndices_1file

Extract Modification Indices for One File
extractSummaries_1plan

Worker function used in extractSummaries_1section
extractTech15

Extract Technical 15 from Mplus
getInitTags

Get Initial Tags
extractSummaries_1section

Extract summary information for one section from Mplus output
extractTech1

Extract Technical 1 matrix from Mplus
extractModIndices

(DEPRECATED) Extract model modification indices.
extractSampstat

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

Extract Technical 12 from Mplus
extractFreeFile

Extract free file output
extractR3step

Extract output of R3STEP procedure
extractParameters_1file

Extract Parameters for One File
extractModelSummaries

(DEPRECATED) Extract summary statistics from a single output file or from a group of Mplus models within a directory
extractTech4

Extract Technical 4 matrix from Mplus
extractSummaries_1file

Extract the summaries from one file
get_results

Extract Mplus results
extractResiduals

Extract residual matrices
extractTech9

Extract Technical 9 matrix from Mplus
extractWarningsErrors_1file

Extract warnings and errors from 1 mplus file
extractTech8

Extract Technical 8 from Mplus
extractEFAparameters

Extract the model parameters from an EFA Mplus model output
getMultilineSection

Extract a multiline section from Mplus output
extractTech3

Extract Technical 3 matrix from Mplus
extractTech7

Extract Technical 7 from Mplus
graphModel

Create a graphic model from Mplus
extractValue

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

helper function to filter a set of Mplus input files based on whether the corresponding .out file already exists
getSavedata_Fileinfo

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

Finalize Init Collection
long2LGMM

Long data to wide latent growth mixture model
friendlyGregexpr

Friendly Regular Expression
getSavedata_readRawFile

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

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

Check whether a useable function argument was provided
l_getSavedata_Bparams

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

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

Simple tag lookup
extractTech10

Extract Technical 10 matrix from Mplus
getOutFileList

Get Output File List
l_getSavedata_Fileinfo

local function that does the work of getSaveData_Fileinfo
getSection

Get an Output Section
matrixExtract

Reconstruct matrix from multi-line text output
lookupValue

Lookup values
get_job_status

This function checks the status of one or more compute jobs
get_efa_nfactors

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

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

Lookup the matrix element for a give parameter number
lcademo

Latent Class Analysis Demonstration
mplusGLM

Function to fit GLMs in Mplus
mplusModel

Create an mplusModel object for a given model
minutes_to_dhms

helper function to convert a number of minutes into a dhms-formatted string for submission
mplusAvailable

Check whether Mplus can be found
mplus.traceplot

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

mplusModel R6 class
mplusModeler

Create, run, and read Mplus models.
mixtureSummaryTable

Create a summary table of Mplus mixture models
mplusObject

Create an Mplus model object
mplusRcov

Create Mplus code for various residual covariance structures.
parseTags

Parses tags in the body section
parseMplusSyntax

Convert an Mplus syntax string into a parsed list
plotLTA

Plot latent transition model
parseMplus

Check Mplus code for missing semicolons or too long lines.
plot.mplusObject

Plot coefficients for an mplusObject
mplus_as.numeric

Convert Mplus Number to Numeric
plotGrowthMixtures

Plot growth mixture models
plotMixtureDensities

Create density plots for mixture models
paramExtract

Extract parameters from a data frame of Mplus estimates
replaceBodyTags

Replace Body Tags
replaceInitTags

Replace Init Tags
readModels

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

Process the Init Section
parseCatOutput

Parse Categorical Output
plotMixtures

Create latent profile plots
prepareMplusData_Mat

Prepare Mplus Data Matrix
print.MplusRstructure

Print an Mplus Residual Structure object
recurseReplace

Recursive replace
processConditionalTags

Process Conditional Tags
prepareMplusData

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

Remove variable name length warnings from Mplus output file
submitModels

Submit Mplus models to a high-performance cluster scheduler
runModels

Run Mplus Models
slurm_job_status

check the status of jobs submitted on a SLURM cluster
runModels_Interactive

Run Mplus Models Using Graphical Interface
splitDFByRow

Split a data frame into a list by rows
subsetModelList

Subset a list of Mplus model results
separateHyphens

Separate Hyphenated Variable Strings
showSummaryTable

Display summary table of Mplus model statistics in separate window
splitFilePath

Split File and Path into Separate Parts
updateCurrentValues

Updates current values
trainLGMM

Train a variety of latent growth mixture model
summary.mplus_submission_df

summary function for submission from submitModels
update.mplusObject

Update an Mplus model object
trimSpace

Trim White Space
unlabeledMatrixExtract

Reconstruct matrix from unlabeled multi-line text output
testBParamConstraint

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

helper function to get the status of jobs on a TORQUE cluster
testBParamCompoundConstraint

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

helper function to validate format of walltime inputs for HPC submission
summary.mplusObject

Summarize an mplusObject
addNode

Add a node to a GRAPHVIZ model
checkSubmission

check on the status of submitted Mplus jobs on the cluster
HTMLSummaryTable

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

Clean data and calculate the md5 hash
OS

Functions to identify the operating system
cd

Change directory
LatexSummaryTable

Display summary table of Mplus model statistics in separate window
classifyTags

Classifies Tags
MplusAutomation

Automating Mplus Model Estimation and Interpretation
SummaryTable

Create a summary table of Mplus model statistics
connectNodes

Connect two nodes
createMixtures

Create syntax for a batch of mixture models
coef.mplus.model

Return coefficients for an mplus.model object