Here's how to use an R script like a Python script, relying on box. While there are reasons to use R, there are also two very bad parts of the R language, avoid them: (1) never use source
and (2) never use library
. These encourage patterns of code that are difficult to test or maintain. Using source
comes along with changing the working directory sometimes, which should also be avoided. I'll quote Jenny Bryan, who, among other things says
Have setwd() in your scripts? PLEASE STOP DOING THAT. ... I will come into your lab and SET YOUR COMPUTER ON FIRE.
She has also written a whole post on why setwd()
is, and I quote again, "so problematic and often associated with other awkward workflow problems".
There are three files here:
src/main/myscript.R
: the main script, has functions that can be used elsewhere and also can be run standalone.src/main/04_unconventional_filename.R
: a script loaded by the main one above. Two purposes for including this: (1) example of using an weird file name, and (2) this script also relied on another script.src/main/utils.R
: your standard utils.
Start with why box to understand the rationale behind it's use. I'll cover a few more specific questions.
- I don't want to use box in every one of my scripts, just a few.
- Just ignore the box lines and
source()
away, it won't hurt that workflow. You don't have to completely refactor.
- Just ignore the box lines and
- How can I have a project that uses box internally, that is loaded by another project.
- On the other project side, it's relatively simple: just don't set
box.path
and continue to load things internally relative to project root. On this side, again it's simple, setbox.path
before loading.
- On the other project side, it's relatively simple: just don't set
- How can a testthat script test a script that uses box.
- This is a tad bit trickier, since the working directory of
testthat
is actually reset to where to the test file is. Nonetheless, this will work.
- This is a tad bit trickier, since the working directory of