【问题标题】:Continuing a while loop after error in R在R中出错后继续while循环
【发布时间】:2015-08-16 19:16:13
【问题描述】:

我正在尝试使用 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
    }
}

任何帮助将不胜感激!

【问题讨论】:

  • tryCatch({...}, silent = TRUE)?
  • 为什么 while 而不是简单的 for??
  • 其中一个比另一个有显着优势吗? (我是个新手)

标签: json r loops while-loop skip


【解决方案1】:

来自 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
}

【讨论】:

  • 谢谢你,Tchotchke!实际上,我刚刚尝试过: if(url.exists("url in question")) { do work} 在尝试 download.file 之前,我将只使用 url.exists。感谢您的建议!
猜你喜欢
  • 1970-01-01
  • 2017-11-21
  • 2023-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多