【问题标题】:How to catch the error, save it and then remove the error in foreach in R?如何捕获错误,保存它,然后在 R 中的 foreach 中删除错误?
【发布时间】:2018-04-04 05:25:39
【问题描述】:

我正在运行一个代码,捕获错误并将其保存以备后用对我来说非常重要,但不要将其包含在我的 foreach 最终结果中。我使用过 trycatch,甚至尝试使用 stop 强制出错。这是我的代码的 sn-p:

##options namely stop , remove or pass 
error_handle <- "remove"

cores <- round(detectCores()*percent)
cl<-makeCluster(cores)
registerDoParallel(cl)
predict_load_all <- foreach(i=1:length(id),.export=func,.packages 
(.packages()),.errorhandling = error_handle) %dopar% {

possibleError <- tryCatch({
weather_cast <- data.frame(udata$date,j,coeff_i,predict(hour_fits[[j]], 
newdata=udata))
},error=function(e)return(paste0("The hour '",j, "'",
                                 " caused the error: '", e, "'")))

if(!exists("weather_cast")){
#possibleError <- data.frame('coeff_item' = coeff_i,'Error' = 
possibleError)
possibleError <- data.frame('Error' = possibleError)
write_csv(possibleError,file.path(path_predict,
'Error_weather_cast.csv'),append = T)
stop('error')
}
colnames(weather_cast)<- c("Date","Hour","coeff_item","Predicted_Load")

ifelse(j==1,predict_load <-weather_cast,predict_load <- 
rbind(predict_load,weather_cast))
predict_load <- spread(predict_load, Hour, Predicted_Load)
predict_load
}

我正在运行 foreach 以输出 predict_load_allpossibleError 是需要保存的错误,由trycatch 绑定。这应该保存对象(满足存在条件),然后使用 stop,引发一个错误,该错误被 remove(.errohandling object) 和 foreach 中的循环忽略被跳过。这样,我得到了错误和没有错误的列表。 这似乎没有保存错误文件。 有什么想法吗?

【问题讨论】:

  • 你不能/不应该用并行循环做一些串行的事情(比如附加到一个文件)。写入单独的文件。无论如何,请提供一个最小的可重现示例。
  • 是的,我明白,但我试图通过执行上述操作来捕捉错误。您是否知道为什么我的上述方法不起作用和/或上述方法的解决方案?

标签: r multithreading try-catch parallel.foreach


【解决方案1】:

根据我的经验(不幸的是,我在并行处理方面的“学习经验”比实际的成功案例要多得多),这不是一件容易的事。我找到的最佳解决方案是将outfile = '' 添加到makeCluster 命令。对我来说,在非交互模式下,这会导致(一些?)错误消息被写入输出文件,而不是被完全丢弃。

【讨论】:

  • outfile 参数是否可以与 .errorhandling 参数一起设置为 remove?它还会捕获错误吗?
猜你喜欢
  • 2019-04-13
  • 2016-10-05
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-29
相关资源
最近更新 更多