Published on *OpenMx* (http://openmx.psyc.virginia.edu)

By *mspiegel*

Created *01/15/2010 - 19:04*

Fri, 01/15/2010 - 19:04 — mspiegel [1]

Below is a function that prints to the console all of the means and covariances matrices in a model and all of the nested submodels. The function .collectMeansCovariances() places all of the matrices into a single list. The remaining lines of showMeansCovariances() are just pretty-printing, they are not interesting.

.collectMeansCovariances() extracts the means and covariances of the top model, and then recursively calls itself to collect the matrices from the submodels. The function does not assume a specific type of objective function. Instead it browses through the slots of the objective function, searching for the slot 'covariance' and the slot 'means'. If those slots are found, then a call to mxEval() must be constructed. It is important to use the as.symbol() when calling the substitute() function, otherwise the covariance name will be interpreted as a regular string instead of a symbol.

Finally, perform the recursive step and then collect the results. The call to unlist() is used because each call to .collectMeansCovariances() returns a list result.

showMeansCovariances <- function(model) { resultsList <- .collectMeansCovariances(model) if(length(resultsList) > 0) { resultsNames <- names(resultsList) for(i in 1:length(resultsList)) { cat(resultsNames[[i]],'\n') print(resultsList[[i]]) cat('\n') } } } .collectMeansCovariances <- function(model) { listReturn <- list() if (!is.null(model$objective)) { objective <- model$objective slots <- slotNames(objective) # extract the covariance if ('covariance' %in% slots) { covName <- objective@covariance covariance <- eval(substitute(mxEval(x, model), list(x = as.symbol(covName)))) listReturn[[covName]] <- covariance } # extract the means if ('means' %in% slots) { meansName <- objective@means means <- eval(substitute(mxEval(x, model), list(x = as.symbol(meansName)))) listReturn[[meansName]] <- means } } # Recursively collect means and covariances of submodels submodels <- lapply(model@submodels, .collectMeansCovariances) listReturn <- append(listReturn, unlist(submodels, FALSE)) return(listReturn) }

**Links:**

[1] http://openmx.psyc.virginia.edu/users/mspiegel

[2] http://openmx.psyc.virginia.edu/thread/392

[3] http://openmx.psyc.virginia.edu/thread/347

[4] http://openmx.psyc.virginia.edu/forums/openmx-help/openmx-general-help