![](/img/trans.png)
[英]Is there any way to have R script continue after receiving error messages instead of halting execution?
[英]How do I avoid halting the execution of a standalone r script that encounters an error?
我正在運行在多語言框架中編寫的優化程序。 因為我依靠不同的語言來完成任務,所以所有內容都必須獨立,以便可以通過批處理文件啟動。 在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接下來要做什么。 這是我迷路的地方。 在詳盡搜索了幾篇文章( 例如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
是使用tryCatch
實現的; 對於編程,代替try(expr, silent = TRUE)
,像tryCatch(expr, error = function(e) e)
(或其他簡單的錯誤處理函數)可能更有效,更靈活。
看一下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]
}
您是否嘗試過在Try函數中將silent參數設置為true?
max<-0
cumR2<-0
adjR2<-0
pvalue<-NA
try({
selMEM <- forward.sel(muskfreq, musk.MEM, adjR2thresh=adjR2)
max<-dim(selMEM)[1]
cumR2<-selMEM$R2Cum[max]
adjR2<-selMEM$AdjR2Cum[max]
pvalue<-selMEM$pval[max]
}, silent=T)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.