如果发生错误,请重试for循环R循环 [英] Retry for-loop R loop if error

查看:202
本文介绍了如果发生错误,请重试for循环R循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个R For循环,该循环从服务器下载数据并将结果添加到表中,但是,有时会出现错误,无法停止该循环.如果我告诉它重做上一次下载并继续,则它可以在下一个错误之前运行另外一段时间. 该错误与代码或数据无关,而是随机的.有时会运行2.5个小时,而有时会在下载相同数据 45分钟后停止.
如果有错误,有没有办法让我的循环后退一步,然后重试? 例如.在

I have an R For loop that downloads data from a server and adds result to table however, I sometimes get an error stopping the loop. If I tell it to redo the last download and continue, it works for another while before the next error. The error isn't with code or data, but is random; sometimes it runs for 2.5 hours, other times it stops after 45 minutes downloading the same data.
Is there a way I could get my loop to take a step back if there is an error and retry? eg. in

for (i in 1:1000){
    table[i,] <- downloadfnc("URL", file = i)
}

让我说我在下载i = 500时遇到错误,我要做的就是:

lets say I get an error while it was downloading i=500, all I do to fix is:

for (i in 500:1000){
    i <- i + 499     #since i starts at 1, 499+1=500
    table[i,] <- downloadfnc("URL",file = i)
}

然后,即使上次出现错误,它也会下载文件"500". 有没有一种方法可以使它自动化,以便在出现错误时退后一步(i-1)并重试(可能会有几秒钟的延迟)?

then it downloads file"500" even though it got an error last time. is there a way I could automate it, so that if there is an error, it takes a step back (i-1) and retry it (perhaps with a few seconds delay)?

(因为仅使用R了几个星期,所以请基本谈谈)

(been using R for only several weeks, so basic talk please)

推荐答案

您可以抛出try-catch组合.

You could throw a try-catch combo.

for (i in 1:1000){
    while(TRUE){
       df <- try(downloadfnc("URL", file = i), silent=TRUE)
       if(!is(df, 'try-error')) break
    }
    table[i,] <- df
}

这将在while循环内继续进行,直到成功下载文件为止,并且仅在成功下载后继续进行.

This will continue within the while loop until the file is successfully downloaded, and only move on when it is successfully downloaded.

这篇关于如果发生错误,请重试for循环R循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆