在 R 出错后继续 while 循环

Continuing a while loop after error in R

我正在尝试使用 while 循环下载一堆 JSON 个文件。

它们的编号从 255 到 1。但是,其中一些缺失(例如,238.json 不存在)。

scheduleurl <- "http://blah.blahblah.com/schedulejsonfile="
i <- 255
while ( i > 0) {

    last = paste0(as.character(i), ".json")
    path = "/Users/User/Desktop/Temp"
    fullpath = paste0(path, last)
    ithscheduleurl <- paste0(scheduleurl, as.character(i))
    download.file(ithscheduleurl, fullpath)
    i <- i - 1
    }

我基本上想编写我的 while 循环,如果它遇到一个不存在的文件(当 i = 238 时它会),它基本上继续到 237 而不是停止。

我以这种方式尝试了 tryCatch() 函数,但它不起作用(继续尝试相同的 URL):

while ( i > 0) {
    possibleError <- tryCatch({
    last = paste0(as.character(i), ".json")
    path = "/Users/dlopez/Desktop/Temp"
    fullpath = paste0(path, last)
    ithscheduleurl <- paste0(scheduleurl, as.character(i))
    download.file(ithscheduleurl, fullpath)
    i <- i - 1}
    , error=function(e) e) 

    if(inherits(possibleError, "error")) {
            next
    }
}

如有任何帮助,我们将不胜感激!

来自 RCurl 包的

url.exists 应该可以解决问题。

library(RCurl)

while ( i > 0) {

last = paste0(as.character(i), ".json")
path = "/Users/User/Desktop/Temp"
fullpath = paste0(path, last)
ithscheduleurl <- paste0(scheduleurl, as.character(i))
if (url.exists(ithscheduleurl)) {
download.file(ithscheduleurl, fullpath)
}
i <- i - 1
}