Learn R Programming

⚠️There's a newer version (1.1.1) 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

4,629

Version

1.1.0

License

LGPL-3

Maintainer

Michael Hallquist

Last Published

April 6th, 2022

Functions in MplusAutomation (1.1.0)

cd

Change directory
MplusAutomation

Automating Mplus Model Estimation and Interpretation
.cleanHashData

Clean data and calculate the md5 hash
LatexSummaryTable

Display summary table of Mplus model statistics in separate window
addHeaderToSavedata

Add header to saved data
HTMLSummaryTable

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

Add a node to a GRAPHVIZ model
classifyTags

Classifies Tags
OS

Functions to identify the operating system
SummaryTable

Create a summary table of Mplus model statistics
createVarSyntax

Create Mplus syntax for variable names
connectNodes

Connect two nodes
coef.mplus.model

Return coefficients for an mplus.model object
clipString

Clip String
createModels

Create Mplus Input Files from Template
createMixtures

Create syntax for a batch of mixture models
detectColumnNames

Detect Column Names
createSyntax

Create the Mplus input text for an mplusObject
.convertData

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

Divide text into fields
extractEFAparameters

Extract the model parameters from an EFA Mplus model output
extractFacScoreStats

Extract Factor Score Statistics
detectMplus

Detect the location/name of the Mplus command
extractIndirect

Extract Indirect Effects output
extractDataSummary

Function to extract the SUMMARY OF DATA section from Mplus outputs
confint.mplus.model

Return confidence intervals for an mplus.model object
extractClassCounts

Extract Latent Class Counts
extractModIndices_1file

Extract Modification Indices for One File
compareModels

Compare the output of two Mplus models
extractModelParameters

Extract model parameters from MODEL RESULTS section.
extractFreeFile

Extract free file output
detectVariables

Automatically detect variables from an Mplus model object
.mplusMultinomial

Internal Function for Multinomial Regression in Mplus
extractModIndices

Extract model modification indices.
getSavedata_Data

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

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

Extract Parameters for One File
lcademo

Latent Class Analysis Demonstration
extractParameters_1section

Extract Parameters for One Section
long2LGMM

Long data to wide latent growth mixture model
extractIndirect_section

Extract Indirect Effects output
extractResiduals

Extract residual matrices
extractSampstat

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

Extract and parse Mplus input file
evaluateConditional

Evaluate Conditional
extract

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

Extract Parameters for One Chunk
extractTech4

Extract Technical 4 matrix from Mplus
extractModelSummaries

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

Extract Technical 3 matrix from Mplus
extractTech15

Extract Technical 15 from Mplus
extractTech12

Extract Technical 12 from Mplus
extractResiduals_1section

Helper subfunction to extract one section of OUTPUT: RESIDUALS Can be called multiple times, as in the case of invariance testing
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
extractSummaries_1file

Extract the summaries from one file
extractSummaries_1plan

Worker function used in extractSummaries_1section
extractAux

Extract Auxiliary condition means and comparisons.
extractTech7

Extract Technical 7 from Mplus
extractModIndices_1chunk

Extract Modification Indices for One Chunk (Section)
getSavedata_Fileinfo

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

Check whether a useable function argument was provided
getSection

Get an Output Section
extractTech8

Extract Technical 8 from Mplus
getMultilineSection

Extract a multiline section from Mplus output
getOutFileList

Get Output File List
getInitTags

Get Initial Tags
friendlyGregexpr

Friendly Regular Expression
prepareMplusData_Mat

Prepare Mplus Data Matrix
plotLTA

Plot latent transition model
lookupTech1Parameter

Lookup the matrix element for a give parameter number
print.MplusRstructure

Print an Mplus Residual Structure object
lookupSimpleTags

Simple tag lookup
plotMixtureDensities

Create density plots for mixture models
extractSummaries_1section

Extract summary information for one section from Mplus output
extractTech1

Extract Technical 1 matrix from Mplus
separateHyphens

Separate Hyphenated Variable Strings
runModels_Interactive

Run Mplus Models Using Graphical Interface
lookupValue

Lookup values
mplus.traceplot

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

Create a graphic model from Mplus
trimSpace

Trim White Space
htmlout

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

Create a summary table of Mplus mixture models
paramExtract

Extract parameters from a data frame of Mplus estimates
unlabeledMatrixExtract

Reconstruct matrix from unlabeled multi-line text output
extractWarningsErrors_1file

Extract warnings and errors from 1 mplus file
finalizeInitCollection

Finalize Init Collection
extractTech10

Extract Technical 10 matrix from Mplus
mplusGLM

Function to fit GLMs in Mplus
rmVarWarnings

Remove variable name length warnings from Mplus output file
l_getSavedata_Fileinfo

local function that does the work of getSaveData_Fileinfo
recurseReplace

Recursive replace
mplusAvailable

Check whether Mplus can be found
l_getSavedata_readRawFile

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
readModels

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

Run Mplus Models
plot.mplusObject

Plot coefficients for an mplusObject
l_getSavedata_Bparams

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

Process the Init Section
processConditionalTags

Process Conditional Tags
parseCatOutput

Parse Categorical Output
splitFilePath

Split File and Path into Separate Parts
subsetModelList

Subset a list of Mplus model results
plotGrowthMixtures

Plot growth mixture models
plotMixtures

Create latent profile plots
mplusObject

Create an Mplus model object
get_results

Extract Mplus results
mplusModeler

Create, run, and read Mplus models.
matrixExtract

Reconstruct matrix from multi-line text output
updateCurrentValues

Updates current values
update.mplusObject

Update an Mplus model object
mplus_as.numeric

Convert Mplus Number to Numeric
mplusRcov

Create Mplus code for various residual covariance structures.
summary.mplusObject

Summarize an mplusObject
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
parseTags

Parses tags in the body section
replaceBodyTags

Replace Body Tags
parseMplus

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

Train a variety of latent growth mixture model
replaceInitTags

Replace Init Tags
testBParamConstraint

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

Split a data frame into a list by rows
showSummaryTable

Display summary table of Mplus model statistics in separate window