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.0.0

License

LGPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

Michael Hallquist

Last Published

July 1st, 2021

Functions in MplusAutomation (1.0.0)

classifyTags

Classifies Tags
.cleanHashData

Clean data and calculate the md5 hash
SummaryTable

Create a summary table of Mplus model statistics
MplusAutomation

Automating Mplus Model Estimation and Interpretation
cd

Change directory
addNode

Add a node to a GRAPHVIZ model
OS

Functions to identify the operating system
addHeaderToSavedata

Add header to saved data
HTMLSummaryTable

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

Display summary table of Mplus model statistics in separate window
createModels

Create Mplus Input Files from Template
extract

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

Connect two nodes
detectMplus

Detect the location/name of the Mplus command
createMixtures

Create syntax for a batch of mixture models
extractAux

Extract Auxiliary condition means and comparisons.
detectColumnNames

Detect Column Names
createSyntax

Create the Mplus input text for an mplusObject
detectVariables

Automatically detect variables from an Mplus model object
compareModels

Compare the output of two Mplus models
confint.mplus.model

Return confidence intervals for an mplus.model object
createVarSyntax

Create Mplus syntax for variable names
clipString

Clip String
extractEFAparameters

Extract the model parameters from an EFA Mplus model output
extractModIndices_1file

Extract Modification Indices for One File
divideIntoFields

Divide text into fields
extractParameters_1file

Extract Parameters for One File
extractParameters_1section

Extract Parameters for One Section
extractModelParameters

Extract model parameters from MODEL RESULTS section.
extractTech3

Extract Technical 3 matrix from Mplus
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
extractFacScoreStats

Extract Factor Score Statistics
extractParameters_1chunk

Extract Parameters for One Chunk
.convertData

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

Return coefficients for an mplus.model object
extractClassCounts

Extract Latent Class Counts
extractDataSummary

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

Extract free file output
extractSampstat

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

Extract Indirect Effects output
extractWarningsErrors_1file

Extract warnings and errors from 1 mplus file
extractTech12

Extract Technical 12 from Mplus
extractTech15

Extract Technical 15 from Mplus
.mplusMultinomial

Internal Function for Multinomial Regression in Mplus
getSavedata_Bparams

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

Extract residual matrices
extractTech1

Extract Technical 1 matrix 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
extractTech10

Extract Technical 10 matrix from Mplus
getMultilineSection

Extract a multiline section from Mplus output
finalizeInitCollection

Finalize Init Collection
long2LGMM

Long data to wide latent growth mixture model
lcademo

Latent Class Analysis Demonstration
getSavedata_Data

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

Check whether Mplus can be found
mplusGLM

Function to fit GLMs in Mplus
paramExtract

Extract parameters from a data frame of Mplus estimates
parseCatOutput

Parse Categorical Output
evaluateConditional

Evaluate Conditional
l_getSavedata_readRawFile

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

local function that does the work of getSaveData_Fileinfo
getOutFileList

Get Output File List
graphModel

Create a graphic model from Mplus
htmlout

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

Extract Indirect Effects output
friendlyGregexpr

Friendly Regular Expression
extractModIndices

Extract model modification indices.
extractSummaries_1plan

Worker function used in extractSummaries_1section
extractSummaries_1section

Extract summary information for one section from Mplus output
extractModIndices_1chunk

Extract Modification Indices for One Chunk (Section)
getInitTags

Get Initial Tags
extractInput_1file

Extract and parse Mplus input file
lookupValue

Lookup values
extractTech7

Extract Technical 7 from Mplus
mplusModeler

Create, run, and read Mplus models.
matrixExtract

Reconstruct matrix from multi-line text output
recurseReplace

Recursive replace
mplusObject

Create an Mplus model object
parseMplus

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

Check whether a useable function argument was provided
mplusRcov

Create Mplus code for various residual covariance structures.
readModels

Read Parameters, Summary Statistics, and Savedata from Mplus Output
mplus_as.numeric

Convert Mplus Number to Numeric
parseTags

Parses tags in the body section
processConditionalTags

Process Conditional Tags
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
extractTech8

Extract Technical 8 from Mplus
l_getSavedata_Bparams

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

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

Prepare Mplus Data Matrix
get_results

Extract Mplus results
getSection

Get an Output Section
get_efa_nfactors

Small helper function to obtain number of factors for an EFA output section
print.MplusRstructure

Print an Mplus Residual Structure object
showSummaryTable

Display summary table of Mplus model statistics in separate window
mixtureSummaryTable

Create a summary table of Mplus mixture models
rmVarWarnings

Remove variable name length warnings from Mplus output file
runModels

Run Mplus Models
processInit

Process the Init Section
splitDFByRow

Split a data frame into a list by rows
subsetModelList

Subset a list of Mplus model results
trimSpace

Trim White Space
splitFilePath

Split File and Path into Separate Parts
mplus.traceplot

Plot the samples for each MCMC chain as a function of iterations
plot.mplusObject

Plot coefficients for an mplusObject
testBParamConstraint

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

Reconstruct matrix from unlabeled multi-line text output
lookupSimpleTags

Simple tag lookup
plotGrowthMixtures

Plot growth mixture models
plotLTA

Plot latent transition model
lookupTech1Parameter

Lookup the matrix element for a give parameter number
trainLGMM

Train a variety of latent growth mixture model
plotMixtures

Create latent profile plots
plotMixtureDensities

Create density plots for mixture models
prepareMplusData

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

Replace Body Tags
summary.mplusObject

Summarize an mplusObject
replaceInitTags

Replace Init Tags
runModels_Interactive

Run Mplus Models Using Graphical Interface
update.mplusObject

Update an Mplus model object
separateHyphens

Separate Hyphenated Variable Strings
testBParamCompoundConstraint

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

Updates current values