# NOT RUN {
# Create and fit a WLS model using RAM, and then using matrices.
library(OpenMx)
# Simulate some data where y = .5x + error
x = rnorm(1000, mean = 0, sd = 1)
y = 0.5*x + rnorm(1000, mean = 0, sd = 1)
tmpFrame = data.frame(x, y)
varNames = names(tmpFrame)
# =======================
# = A RAM model example =
# =======================
m1 = mxModel("my_first_WLS", type="RAM",
manifestVars = c("x", "y"),
mxPath(c("x", "y"), arrows=2, values=1),
mxPath("x", to="y"),
mxFitFunctionWLS(),
mxData(tmpFrame, 'raw')
)
m1 = mxRun(m1)
summary(m1)$parameters
originalSE <- m1$output$standardErrors
# Here are the summary statistics
print(m1$data$observedStats)
# Use a different weight matrix
os <- m1$data$observedStats
os$acov <- rWishart(1, nrow(tmpFrame)/2, diag(3))[,,1]
os$fullWeight <- os$acov
m1$data$observedStats <- os
# Can check whether our new weights are used
m1$data$verbose <- 1L
# Run model
m1 <- mxRun(m1)
# SE indeed changed due to new weights
print(m1$output$standardErrors - originalSE)
# ==========================
# = A matrix-based example =
# ==========================
# Define matrices for Symmetric (S) and Asymmetric (A) paths and an Identity matrix.
S <- mxMatrix(type = "Full", nrow = 2, ncol = 2, values=c(1,0,0,1),
free=c(TRUE,FALSE,FALSE,TRUE), labels=c("Vx", NA, NA, "Vy"), name = "S")
A <- mxMatrix(type = "Full", nrow = 2, ncol = 2, values=c(0,1,0,0),
free=c(FALSE,TRUE,FALSE,FALSE), labels=c(NA, "b", NA, NA), name = "A")
I <- mxMatrix(type="Iden", nrow=2, ncol=2, name="I")
# Build the model
tmpModel <- mxModel(model="exampleModel",
# Add the S, A, and I matrices constructed above
S, A, I,
# Define the expectation
mxAlgebra(name="expCov", solve(I-A) %*% S %*% t(solve(I-A))),
# Choose a normal expectation and WLS as the fit function
mxExpectationNormal(covariance= "expCov", dimnames= varNames),
mxFitFunctionWLS(),
# Add the data
mxData(tmpFrame, 'raw')
)
# Fit the model and print a summary
tmpModel <- mxRun(tmpModel)
summary(tmpModel)
# }
Run the code above in your browser using DataLab