how to automatically restart the execution of a R script if its execution is interrupted

I have a script that constantly performs a set of calculations in an endless loop. But often there are various errors that I cannot predict and the script stops working. I would like to automatically restart the script every time it stops working, and I don't care why the error occurred, I just want to restart the script. I will cite a deliberately erroneous code that I would like to repeat after an error has been issued.

while (TRUE) {
  1+m
}

Upvotes: 1

Views: 134

Answers (1)

Miff
Miff

Reputation: 7951

The try() and trycatch() funtions are designed to deal with code that might cause errors. In the case of your example code, changing it to:

while (TRUE) {
  try(1+m)
}

will keep trying to do the line that produces an error. If your code inside the loop is multiple lines, you can make it into a block by wrapping it in braces, e.g. :

while (TRUE) {
  try({
      a <- 1+m
      print(a)
     })
}

Upvotes: 1

Related Questions