stevec
stevec

Reputation: 52268

Run multiple lines of code but stop on error in R (from RStudio)?

I have a very long, very delicate script, and I'd like to run each successive line of code only if the previous line succeeded (i.e. didn't error). If any line errors, code execution should cease immediately. Is there any keyboard shortcut inside RStudio that allows us to achieve this (e.g. similar to command + enter, but stopping on error) ?

Example and desired output

If we highlight these lines of code and run them (in either RStudio or R elsewhere, e.g. in the terminal)

2 * 2
b * 5
4 * 4
7 * 1

we see

> 2 * 2
[1] 4
> b * 5
Error: object 'b' not found
> 4 * 4
[1] 16
> 7 * 1
[1] 7

I would like some way such that I would only see

> 2 * 2
[1] 4
> b * 5
Error: object 'b' not found

i.e. code execution stopped at the first error

Notes

I will try to solve this without altering the code itself, preferably with a keyboard shortcut inside RStudio, but am very open to other ideas, e.g setting an option (options())

Upvotes: 2

Views: 729

Answers (1)

Eugene Chong
Eugene Chong

Reputation: 1741

Using Ctrl+Shift+Enter (or Mac equivalent, Command+Shift+Enter) to run a script stops at the first error, so that could be a simple solution.

Upvotes: 4

Related Questions