【发布时间】:2017-11-14 13:41:17
【问题描述】:
我已经阅读了有关 tryCatch() 的文档和其他几个问题,但是,我无法找出我的问题类别的解决方案。
要解决的任务是: 1)有一个从数据帧的第1行到第n行的for循环。 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
}
注意:try() 是“...执行指令...”的一部分
我正在寻找的是一个 tryCatch,当发生停止程序的严重错误时,它会从当前索引“i”重新启动 for 循环。
这个程序将允许我自动迭代超过 400000 行,并在出现错误时在中断的地方重新启动。这意味着该程序将能够完全由人类独立工作。
希望我的问题很清楚,非常感谢。
【问题讨论】:
-
对于从 Internet 下载内容的情况,请使用
httr包中的RETRY()。 -
这对于其他类型的问题也是一个好主意。这里的问题不是从互联网收集数据,而是如何使用 tryCatch()(或其他一些函数)在出现错误的情况下从上一次迭代重新开始循环。
标签: r for-loop error-handling try-catch