examples/monte_carlo/helper_functions.R

## This worker function generates Mplus syntax to estimate a one-factor CFA for each replication. 
## One could easily adapt it to use mplusObject and mplusModeler
getCFASyntax <- function(nc, nv, ss, sep, np, dataSection, output=NULL, savedata=NULL, processors=1) {
  syntax <- paste0(
      "TITLE:\n",
      "  CFA NClass = ", nc, ", NVar = ", nv, ", NCases = ", ss, ", LCSep = ", sep, ", NoiseProp = ", np, "\n",
      dataSection,
      "VARIABLE:\n",
      "  NAMES ARE ", paste0("x", 1:nv, collapse=" "), " trueclas;\n",
      "  USEVARIABLES ARE ", paste0("x", 1:nv, collapse=" "), ";\n",
      "ANALYSIS:\n",
      "  TYPE = GENERAL;\n",
      "  ESTIMATOR=MLR;\n",
      "  PROCESSORS=", processors, " 1;\n",
      "  ITERATIONS = 2000;\n",
      "  SDITERATIONS = 50;\n",
      "  MITERATIONS = 2000;\n",
      "MODEL:\n",
      "  fac BY ", paste0("x1-x", nv, "*1"), ";\n",
      "  fac@1; !fix var to 1 for identification\n",
      "  [", paste0("x1-x", nv, "*0"), "];\n", #zero means by default
      "\n",
      output,
      savedata
  )
  return(syntax)
}

## This worker function generates Mplus syntax to estimate an LCA model for each replication. 
## One could easily adapt it to use mplusObject and mplusModeler
getFMMSyntax <- function(fc, nc, nv, ss, sep, np, dataSection, propMeans=NULL, means=NULL, output=NULL, savedata=NULL, processors=1) {
  syntax <- paste0(
      "TITLE:\n",
      "  FitClass = ", fc, ", NClass = ", nc, ", NVar = ", nv, ", NCases = ", ss, ", LCSep = ", sep, ", NoisePct = ", np, "\n",
      dataSection,
      "VARIABLE:\n",
      "  NAMES ARE ", paste0("x", 1:nv, collapse=" "), " trueclas;\n",
      "  USEVARIABLES ARE ", paste0("x", 1:nv, collapse=" "), ";\n",
      "  CLASSES=c(", fc, ");\n",
      "ANALYSIS:\n",
      "  STARTS = 350 35;\n",
      "  TYPE = MIXTURE;\n",
      "  ESTIMATOR=MLR;\n",
      "  PROCESSORS=", processors, " 1;\n",
      "MODEL:\n",
      "  %OVERALL%\n",
      "  ", paste0("x1-x", nv, "*1"), ";\n",
      propMeans,
      "\n",
      means,
      output,
      savedata
  )
  return(syntax)
}

##cleanup temporary files generated by Mplus
cleanupTempFiles <- function(dir=tempdir()) {
  unlink(c(
          file.path(tempdir(), "external_montecarlo_rep*.dat"),
          file.path(tempdir(), "*.tst"), #sometimes left behind by Mplus
          file.path(tempdir(), "external_montecarlo_rep*.dat"),
          file.path(tempdir(), "external_montecarlo_list.dat"),
          file.path(tempdir(), "individual_rep.inp"),
          file.path(tempdir(), "individual_rep.out"),
          file.path(tempdir(), "cprobs.dat")
      ))     
}
michaelhallquist/MplusAutomation documentation built on March 14, 2024, 11:03 a.m.