Running job
s in clean sessions is a great to test code
in isolation without having to launch new RStudio applications.
Here’s an embarrassing error I commit too often: Say I want to write a function that computes the Mean Squared Error (MSE) of a numerical vector. First, I fiddle around with it in the console, ending up with:
## [1] 4.016175
It works! Then I wrap the code in a function and try it out:
## [1] 4.016175
Huh!? It runs but the MSE should be around 1 here, not 4.
You can select the code and click the addin “Run selection as job in
empty session”. Or you can do the exact same action using code via
job::empty()
:
In the job, you’ll see the error message:
#> Error in mean((tmp - mean(tmp))^2) : object 'tmp' not found
Aha, by running the code in a separate session, we learned that it
only seemed to work because I had the tmp
variable
lingering in my environment. Errors like this become less trivial as the
code (and your environment) grows more complex.
In the example above, you can, of course, import
selectively too. These two jobs are identical, but I prefer the
first.
testthat
unit tests have access to your current
environment so it is prone to the kind of errors introduced above.
job::empty()
to the rescue:
This also frees up your console in the meantime.