1

我使用循环插入的download.file函数在 Internet 上下载数据。我的循环看起来像这样:

for (i in 1:9999999) {

      download.file(paste("website_path",file[i],sep = ""),
                    paste("home_path", file_name[i], sep = ""),
                    mode="wb")

}

它运行良好,但有时会出现错误消息。当我手动重新启动循环时,再次出现错误消息,但对于另一个文件(这次出现错误消息的前一个文件已下载)

因此,我正在寻找一个命令,它允许我在出现错误消息后自动重新启动 for 循环

感谢帮助

4

2 回答 2

1

你有没有考虑try(download.file(...))在你的循环中使用?例子:

func <- function(i){if(i==3||i==7) (stop("no 3 or 7")) else(i)} #returns errors for 3 or 7
for(i in 1:10)(print(func(i)))
#[1] 1
#[1] 2
# Error in func(i) : no 3 or 7
for(i in 1:10)(try(print(func(i))))
#[1] 1
#[1] 2
#Error in func(i) : no 3 or 7
#[1] 4
#[1] 5
#[1] 6
#Error in func(i) : no 3 or 7
#[1] 8
#[1] 9
#[1] 10
于 2018-01-11T17:30:24.070 回答
1

考虑包装该方法tryCatch以捕获任何引发的警告或错误。如果其中任何一个发生在不同的return().

for (i in 1:9999999) {

   url  <- paste0("website_path", file[i])
   home <- paste0("home_path", file_name[i])

   tryCatch({
      download.file(url, home, mode="wb")

    },  warning = function(w) {
          print(paste("WARNING for", url, "   :" w))
          # ... other needed warning handler

    },  error = function(e) {
          print(paste("ERROR for", url, "   :" e))
          # ... other needed error handler

    }
  )

}
于 2018-01-11T17:30:41.520 回答