You are here

helper-functions

Primary tabs

Wiki home pageIdeas and example functions that extend OpenMx, encapsulate tedious work, and make scripts easier to write or more compact.

You will probably define helper functions, especially for summarising the output of model you use frequently.

There are libraries of helpers that work with OpenMx including

  • https://github.com/tbates/umx
  • install.packages("semTools")

Some how-to helpers are listed here:

Read a Lower triangle file

source

readLowerTriangle <- function(file, nrows, fill=TRUE) {
    xvector <- scan(file)
    X <- matrix(NA, nrows, nrows)
    i <- 1
    for(row in 1:nrows) {
        for(col in 1:nrows) {
            if(col>row) next
            X[row,col] <- xvector[i]
            i <- i + 1
            if (fill)
                X[col,row] <- X[row,col]
        }
    }
    return(X)
}

An alternative using matrix indexing would be:

read.lower.triangle <- function(file, nrows) {
  X <- matrix(NA, ncol=nrows, nrow=nrows)
  X[upper.tri(X, diag=TRUE)] <- scan(file)
  X[lower.tri(X, diag=FALSE)] <- t(X)[lower.tri(X, diag=FALSE)]
  return(X)
}

See also read.moments() in http://cran.r-project.org/web/packages/sem/sem.pdf

require(sem) # install.packages("sem", dep=T)
read.moments(file = "", diag = TRUE,
names = as.character(paste("X", 1:n, sep = "")))

Converting a correlation matrix to a covariance matrix

If you are reanalysing published data, you may only have a correlation matrix and the SD for each variable. You can upconvert this to a covariance matrix with cor2cov(matrix, sd) from the MBESS package

http://rss.acs.unt.edu/Rdoc/library/MBESS/html/cor2cov.html