2

This is interesting. I'm on CentOS 6.9, R-3.4.2. I have a code, tmp.R:

main<-function(){
    a = 9
    print(a) xyz
    print("Should never get here")
}

When I run this, Rscript tmp.R, I get

Error: unexpected symbol in:
"    a = 9
    print(a) xyz"
No traceback available
[1] "Should never get here"
Error: unexpected '}' in "}"
No traceback available

This is pretty confusing because I never actually called main(). In fact, if I remove the syntax error (3rd line becomes print(a)), and I run it, there isn't any output. This is the expected behavior in my mind.

QUESTION : Why does R execute code in a script when a syntax error occurs, even when the code isn't explicitly called(!)?

EDIT : It turns out that this behavior seems to be due to having options(error=traceback) being set in my .Rprofile. This is undesirable behavior none the less. It would still be desirable to be able to get tracebacks when in interactive mode and not do this strange code execution in non-interactive mode.

irritable_phd_syndrome
  • 4,631
  • 3
  • 32
  • 60
  • 1
    It isn't executing the code, it's *parsing* it in order to store it as an object in the calling environment. In this case, the parsing fails, not the execution of it. (This should be the case with `Rscript` or in the R console itself. Similarly, try `a <- list(x=1 y=2)` ... the object `a` is never created, because the creation of the contents of that object does not parse without error.) – r2evans Oct 22 '18 at 16:20
  • 1
    Are you sure this is the output you get when you call Rscript (and not just `source()`-ing the file)? I do not get the same behavior (running R 3.4.4). – MrFlick Oct 22 '18 at 16:23
  • 1
    @r2evans but the line `[1] "Should never get here"` should only be printed during evaluation, not parsing. That "[1]" part is a big indicator that it's actually being evaluated, no? – MrFlick Oct 22 '18 at 16:24
  • @MrFlick : This is indeed the output of running `Rscript`. @r2evans : Is there a way to suppress this annoying output? Related : https://stackoverflow.com/questions/52932440/stopping-r-code-execution-upon-error-when-run-as-non-interactive-rscript?noredirect=1#comment92775257_52932440 – irritable_phd_syndrome Oct 22 '18 at 16:25
  • 4
    So, the it seems that the issue is with `options(error=traceback)` in `.Rprofile`. When I comment it out, the script ends without executing the last print statement (as expected) – irritable_phd_syndrome Oct 22 '18 at 16:31
  • I see your point, good sleuthing. – r2evans Oct 22 '18 at 16:35
  • Your `.Rprofile` can use `if (interactive()) {options(error=traceback)}` to conditionally change the error behavior during interactive and non-interactive sessions. – MrFlick Oct 22 '18 at 17:18

0 Answers0