简体   繁体   中英

Continue for loop in R after error (example using vector of numbers and letters)

I'm currently working on a project where I'm trying complete a task in a for loop. There are a lot of areas where something can go wrong (it involves creating a pdf report via rmarkdown), but in this case I don't care if something goes wrong, I just want the for loop to keep going.

In the toy example below I would like to be able to print off the numbers 2 through 16, while skipping over the letter 'a'.

something<-function(x){
print(x + 1)
}

for(i in c(1:10,'a',11:15))
{
  res <- try(something(i))
  if(inherits(res, "try-error"))
  {
    #error handling code, maybe just skip this iteration using
    next
  }
  #rest of iteration for case of no error
}

This is loosely based on the example provided in the answer below.

R Script - How to Continue Code Execution on Error .

I've tried adapting several other "how do I continue a for loop in R" to no success.

I'm not a full time programmer, so I'm convinced I'm missing something very simple, but any help would be appreciated.

I had a similar issue, where I had a function I was running in a for loop and needed it to keep running if error comes up. Here's how I did it:

OutputStorage=list()

for (i in 1:k){
  Output=tryCatch(examplefunction(x), error=function(e) NULL)
  OutputStorage[[i]]=Output
}

So if there is an output, it's stored in the list and if not, NULL is stored for that. I think it's working; running it just now actually. Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM