OpenMx报错:无法找到已定义引用cov_matrix,求技术解决方案
解决OpenMx中mxRun报错:Unknown reference 'cov_matrix'的问题
问题描述
我是首次使用R语言的学生,运行到fit <- mxRun(model)时反复报错,之前代码都正常。试过添加model$CovarianceMatrix <- cov_matrix修复没用,怀疑和数据格式有关。
相关代码
pheno2 <- read.csv("pheno2.csv") library(OpenMx) colnames(pheno2) <- gsub("\\.", "_", colnames(pheno2)) num_variables <- 7 cov_matrix <- mxMatrix(type = "Full", nrow = num_variables, ncol = num_variables, free = TRUE, values = 1, name = "cov") means <- mxMatrix(type = "Full", nrow = 1, ncol = num_variables, free = TRUE, values = 0, name = "means") variances <- mxMatrix(type = "Diag", nrow = num_variables, ncol = num_variables, free = TRUE, values = 1, name = "variances") mxDataObject <- mxData(observed = as.matrix(pheno2), type = "raw") expectation <- mxExpectationNormal(covariance = "predicted_cov", means = "means") model <- mxModel("BasicModel", cov_matrix, means, variances, mxAlgebra(cov_matrix %*% t(variances) %*% cov_matrix, name = "predicted_cov"), expectation, mxDataObject) model$CovarianceMatrix <- cov_matrix model$fitFunction <- mxFitFunctionML() fit <- mxRun(model)
报错信息
Error: Unknown reference 'cov_matrix' detected in the entity 'predicted_cov' in model 'BasicModel'
问题原因
报错核心是OpenMx模型内部只识别你给矩阵指定的name参数值,不是R环境里的变量名。你定义cov_matrix时给的name是"cov",但在mxAlgebra里却用了R变量名cov_matrix,模型找不到这个名字的组件,所以报错。另外你加的model$CovarianceMatrix <- cov_matrix完全多余,甚至会干扰模型逻辑。
修复方案
直接修改mxAlgebra里的引用,同时调整模型的规范写法:
修改后的完整代码
pheno2 <- read.csv("pheno2.csv") library(OpenMx) colnames(pheno2) <- gsub("\\.", "_", colnames(pheno2)) # 处理数据缺失值,确保是纯数值型 pheno2 <- na.omit(pheno2) # 自动获取变量数,避免手动输入错误 num_variables <- ncol(pheno2) cov_matrix <- mxMatrix(type = "Full", nrow = num_variables, ncol = num_variables, free = TRUE, values = 1, name = "cov") means <- mxMatrix(type = "Full", nrow = 1, ncol = num_variables, free = TRUE, values = 0, name = "means") variances <- mxMatrix(type = "Diag", nrow = num_variables, ncol = num_variables, free = TRUE, values = 1, name = "variances") mxDataObject <- mxData(observed = as.matrix(pheno2), type = "raw") expectation <- mxExpectationNormal(covariance = "predicted_cov", means = "means") model <- mxModel("BasicModel", cov_matrix, means, variances, # 把R变量名cov_matrix换成模型内的矩阵名cov mxAlgebra(cov %*% t(variances) %*% cov, name = "predicted_cov"), expectation, mxDataObject, # 直接在模型定义时加入拟合函数,不用后续赋值 mxFitFunctionML()) fit <- mxRun(model)
关键修改点
- mxAlgebra引用修正:把
cov_matrix换成你给矩阵定义的namecov,模型内部通过name识别组件,和R变量名无关。 - 移除多余代码:删掉
model$CovarianceMatrix <- cov_matrix,mxExpectationNormal已经指定了协方差来源是predicted_cov,不需要额外赋值。 - 规范拟合函数写法:把
mxFitFunctionML()直接放进mxModel的组件列表里,这是OpenMx的标准写法,避免后续手动赋值可能出现的问题。 - 数据预处理:增加缺失值处理
na.omit(pheno2),同时用ncol(pheno2)自动获取变量数,减少手动输入错误。
内容的提问来源于stack exchange,提问作者Jaewon Lee
相关产品推荐
相关产品推荐

