3

I sometimes paste a list of commands to be executed in the R console. By default, if one command fails (i.e., raises an error), the R console indicates the command has failed, then executes the subsequent commands.

Is there any way to configure the R console so that it stops executing a list of commands whenever one command fails?

Franck Dernoncourt
  • 77,520
  • 72
  • 342
  • 501
  • Possible duplicate of [How to prevent execution of further code steps after error?](https://stackoverflow.com/questions/12573660/how-to-prevent-execution-of-further-code-steps-after-error) – user2100721 Aug 13 '17 at 15:56
  • 1
    There is some overlap but I don't think it's a duplicate. – G. Grothendieck Aug 13 '17 at 16:18

2 Answers2

5

Instead of pasting, run this R command:

source("clipboard")

or if you want to see commands as well as output:

source("clipboard", echo = TRUE)

(or set the verbose option to avoid having to specify echo each time, i.e. options(verbose = TRUE) )

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • 1
    Thanks, that looks very useful too. (obviously the first time I tried `source("clipboard", echo = TRUE)`, I had `source("clipboard", echo = TRUE)` in the clipboard :) ). Also works in PuTTY. – Franck Dernoncourt Aug 13 '17 at 16:00
3

One strategy is to wrap the code in { } so that the code is executed as a single block. For example,

{ceiling(quantile(rnorm(20), seq(0, 1, length.out=8))); rnorm(10)}

will run, but

{ceiling(quantile(rnorm(20), seq(0, 8, length.out=8))); rnorm(10)}

will error out and the second command, rnorm(10) will not run.


d.b. mentions in the comments setting the options(error). According to ?options, by default, this is set to NULL. If you want the code to stop at an error and enter debugging mode, you could type

options(error=recover)

in an initial session or put this into your .Rprofile and then R will enter a debugging mode upon hitting an error.

For the code above, you would see

{ceiling(quantile(rnorm(20), seq(0, 8, length.out=8))); rnorm(10)}

Error in quantile.default(rnorm(20), seq(0, 8, length.out = 8)) :
'probs' outside [0,1]

Enter a frame number, or 0 to exit

1: #1: quantile(rnorm(20), seq(0, 8, length.out = 8)) 2: quantile.default(rnorm(20), seq(0, 8, length.out = 8))

lmo
  • 37,904
  • 9
  • 56
  • 69
  • 2
    @d.b I don't use this regularly, but added some text to address your comment. If you want to add a separate answer that adds more details, I would delete this and up vote yours. – lmo Aug 13 '17 at 15:42