我正在运行我在多语言框架中编写的优化程序。因为我依赖不同的语言来完成任务,所以一切都必须是独立的,以便可以通过批处理文件启动。 2-3 个月来一切都很顺利,但当这个过程的关键部分之一(通过独立的 R 脚本执行)遇到新的东西并给我一条错误消息时,我终于运气不佳了。尽管我尽了最大努力,但此错误消息使一切都戛然而止:
selMEM<-forward.sel(muskfreq, musk.MEM, adjR2thresh=adjR2)
Procedure stopped (adjR2thresh criteria) adjR2cum = 0.000000 with 0 variables (superior to -0.005810)
Error in forward.sel(muskfreq, musk.MEM, adjR2thresh = adjR2) :
No variables selected. Please change your parameters.
我知道为什么收到此消息:它警告我,没有任何变量高于我编程在前向选择期间保留的阈值。虽然这在数百次运行中没有发生,但这没什么大不了的,我只需要告诉 R 下一步要做什么。这就是我迷失的地方。经过对几篇文章( such as here )的详尽搜索后,似乎 try() 和 tryCatch() 是正确的选择。所以我尝试了以下方法:
selMEM<-try(forward.sel(muskfreq, musk.MEM, adjR2thresh=adjR2))
if(inherits(selMEM, "try-error")) {
max<-0
cumR2<-0
adjR2<-0
pvalue<-NA
} else {
max<-dim(selMEM)[1]
cumR2<-selMEM$R2Cum[max]
adjR2<-selMEM$AdjR2Cum[max]
pvalue<-selMEM$pval[max]
}
如果我在 R 中逐行执行有问题的行之后的代码,则它可以完美运行,但是当我从命令提示符将其作为独立脚本执行时,我仍然收到相同的错误消息,并且我的整个过程突然停止在执行下面的操作之前。
关于如何实现这项工作有什么建议吗?
最佳答案
请在 try
帮助中注意这一点:
try
is implemented usingtryCatch
; for programming, instead oftry(expr, silent = TRUE)
, something liketryCatch(expr, error = function(e) e)
(or other simple error handler functions) may be more efficient and flexible.
查看tryCatch
,可能:
selMEM <- tryCatch({
forward.sel(muskfreq, musk.MEM, adjR2thresh=adjR2)
}, error = function(e) {
message(e)
return(NULL)
})
if(is.null(selMEM)) {
max<-0
cumR2<-0
adjR2<-0
pvalue<-NA
} else {
max<-dim(selMEM)[1]
cumR2<-selMEM$R2Cum[max]
adjR2<-selMEM$AdjR2Cum[max]
pvalue<-selMEM$pval[max]
}
关于r - 如何避免停止执行遇到错误的独立 r 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21443107/