Loulou
Loulou

Reputation: 703

Relaunch a for loop after an error message

I download data on internet with the download.file function inserted in a loop. My loop looks like this :

for (i in 1:9999999) {

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

}

It works well, but sometimes an error message occurs. And when I manually relaunch the loop, an error message occurs again but for another file (the former file for which the error message occurs has been downloaded this time)

Therefore, I am looking for a command which allows me to relaunch automatically the for loop after an error message

Thanks for help

Upvotes: 1

Views: 100

Answers (2)

Parfait
Parfait

Reputation: 107767

Consider wrapping the method in tryCatch to catch any raised warning or error. You can even do various processing if either occurs with different 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

    }
  )

}

Upvotes: 1

Eldioo
Eldioo

Reputation: 522

Have you considered using try(download.file(...)) in your loop? Example:

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

Upvotes: 1

Related Questions