我将两个混合效应回归模型拟合到for循环中的数据样本,并将模型摘要写入文件。我将控制台流转移到文本文件,以便我可以跟踪任何警告或错误。我正在使用tryCatch()
处理错误,以便我的循环在错误后不会停止。
据我所知,我的代码有两个问题。首先,当我在tryCatch()
中查询返回的异常时,例如poss.err.mod1
我收到以下错误:
<simpleError in tryCatchList(expr, classes, parentenv, handlers): argument "expr" is missing, with no default>
仍然,警告被正确写入文件,这令人费解。其次,当没有检测到错误时,代码似乎被忽略(即没有模型摘要被写入文件)。所以循环是空的,跳过错误,但显然处理它们而不做任何其他事情。我做错了什么?
N.B。我的代码以this SO post。
为模型# divert console stream to file
options(warn=1)
wngs=file("warnings_log.txt",open="w+",blocking=TRUE)
sink(wngs,type="message")
for(iter in 1:1000){
data = read.csv(paste("sample", iter,".csv", sep=""), header=TRUE)
#error handling case #1
poss.err.mod1 = tryCatch(
lmer(y ~ x1 + (1|ranef), data = data, REML = FALSE), #try part
error=function(e) e #catch part
)
#error handling case #2
poss.err.mod2 = tryCatch(
lmer(y ~ x1 + x2 + (1|ranef), data = data, REML = FALSE), #try part
error=function(e) e #catch part
)
#real work #1
if(!inherits(poss.err.mod1, "error")){
mod1 = lmer(y ~ x1 + (1|ranef1), data = data, REML = FALSE)
write.csv(summmary$mod2, paste("mod2.sum_", iter, ".csv", sep="")
}else{
write(unlist(mod1@optinfo$conv$lme4$messages), paste("mod1.errors_", iter, ".txt", sep=""))
}
#real work #2
if(!inherits(poss.err.mod2, "error")){
mod2 = lmer(y ~ x1 + x2 + (1|ranef1), data = data, REML = FALSE)
write.csv(summmary$mod2, paste("mod2.sum_", iter, ".csv",)
}else{
write(unlist(mod2@optinfo$conv$lme4$messages), paste("mod1.errors_", iter, ".txt", sep=""))
}
cat("Iteration", iter, "completed!\n")
}
#close log file & restore warnings stream to console
closeAllConnections()