2

How do I get an R (version 3.4.2, CentOS 6.9) script to stop on Error instead of happily continuing on? My file :

$ cat tmp.R
a = 9
print(a)
print(b)
print(d)
print("Should never get here")

Running tmp.R non-interactively it:

$ Rscript tmp.R
Looking for libraries in : ~/.R/3.4.2-lib
[1] 9
Error in print(b) : object 'b' not found
Error in print(d) : object 'd' not found
[1] "Should never get here"

Question : How do I get R to stop execution upon encountering an error?

I've tried things like options(error=stop) and options(error=browser) which work in the interactive case but not non-interactive Rscript example.

irritable_phd_syndrome
  • 4,631
  • 3
  • 32
  • 60
  • With R 3.2.3 on ubuntu your script terminates as expected. Is a try-catch possible with a stop() in the catch block? Just checked with R 3.5.1: The script terminates as well after the error. – psychOle Oct 22 '18 at 15:38
  • I don't a priori know where the error will occur and I don't want to use try-catch at every line of my code. It just drives me nuts when an error occurs and causes cascading errors. The real error gets buried behind a bunch of useless output. – irritable_phd_syndrome Oct 22 '18 at 15:42
  • Also, I just tried with R 3.2.3 on CentOS 6.9 and I got the same output as above. It would be silly if this type of behavior is system dependent. – irritable_phd_syndrome Oct 22 '18 at 15:43

1 Answers1

1

This is because I have set options(error=traceback) in my .Rprofile. Commenting it out in my .Rprofile leads to code termination at line 3 as expected. This raises issues with why this generates output. See related questions this and this.

irritable_phd_syndrome
  • 4,631
  • 3
  • 32
  • 60