Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring the R console so that it stops executing a list of commands whenever one command fails

Tags:

r

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?

like image 867
Franck Dernoncourt Avatar asked Dec 12 '25 07:12

Franck Dernoncourt


2 Answers

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) )

like image 189
G. Grothendieck Avatar answered Dec 14 '25 05:12

G. Grothendieck


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))

like image 41
lmo Avatar answered Dec 14 '25 03:12

lmo