R - tryCatch - 使用最后一次迭代索引重新启动for循环

时间:2017-11-14 13:41:17

标签: r for-loop error-handling try-catch

我已经阅读了有关tryCatch()的文档和其他几个问题,但是,我无法找到解决问题的方法。

要解决的任务是: 1)有一个for循环,从数据帧的第1行到第n行。 2)执行一些指令 3)如果错误会停止程序,而是从当前迭代重新启动循环周期。

实施例

for (i in 1:50000) {
...execute instructions...
}

我正在寻找的是一种解决方案,在迭代30250出现错误的情况下,它会重新启动循环,以便

for (i in 30250:50000) {
...execute instructions...
}

我正在研究的实际例子如下:

library(RDSTK)
library(jsonlite)
DF <- (id = seq(1:400000), lat = rep(38.929840, 400000), long = rep( -77.062343, 400000)
for (i in 1 : nrow(DF) {
    location <- NULL
    bo <- 0
    while (bo != 10) {  #re-try the instruction max 10 times per row 
        location <- NULL
        location <- try(location <-  #try to gather the data from internet
                coordinates2politics(DF$lat[i], DF$long[i]))
        if (class(location) == "try-error") {  #if not able to gather the data
            Sys.sleep(runif(1,2,7))  #wait a random time before query again
            print("reconntecting...")
            bo <- bo+1                      
            print(bo)                 
        } else    #if there is NO error
            break   #stop trying on this individual
    }
    location <- lapply(location, jsonlite::fromJSON)
    location <- data.frame(location[[1]]$politics)
    DF$start_country[i] <- location$name[1]
    DF$start_region[i] <- location$name[2]
    Sys.sleep(runif(1,2,7))  #sleep random seconds before starting the new row
}

N.B。:try()是“...执行指令......”的一部分

我正在寻找的是一个tryCatch,当一个停止程序的严重错误发生时,它会从当前索引“i”重新启动for循环。

这个程序允许我自动迭代超过400000行,并在出错的情况下重新启动。这意味着该程序将能够完全独立于人工作。

我希望我的问题很清楚,非常感谢你。

1 个答案:

答案 0 :(得分:2)

使用while而不是for

可以更好地解决这个问题
i <- 1
while(i < 10000){
  tryCatch(doStuff()) -> doStuffResults
  if(class(doStuffResults) != "try-catch") i <- i + 1
{

请注意,如果某些情况总是会失败doStuff:循环永远不会终止!

如果程序会产生致命错误并需要重新启动,那么可以替换第一行i <- 1(只要您不在代码中的其他地方使用i)与

if(!exists("i")) i <- 1

这样循环中的值将保持不变,不会重置为一个。