Now that I have developed some proficiency in writing R code, I longed for a method of modular-izing the code in a fashion similar to the require() functionality in node.js. After much searching on CRAN, I was unable to find what I desired, so I rolled my own!

lrequire() can be found on:

Getting a package accepted into CRAN has a lot to do with reusability and sustainability. Documentation of the package is critical and must adhere to a strict format. In writing the lrequire package, all of the cycles that I spent trying to get it approved were due to documentation. The focus paid off as I extended more effort on documentation, my code improved, tests improved, and I added missing functionality that was certain to be requested as soon as the package was released. Writing the documentation helped me look at the package more like a general user of it and not the author, where I was writing it specifically for my needs.

lrequire() works very much like it’s node.js counterpart – it sources the file into the current environment, using a cached copy of the file if it has already been loaded. There are methods for forcing a reload if necessary, and also follows the module.change_code = 1 method of automatically re-loading the file if changed during the next lrequire() of the file.

Benefits

There are many good reasons to use lrequire(). In no particular order:

  1. Keeps the working environment clean when separating your code into modules. It only exposes those variables you desire to use and not the other variables created in the global namespace in the process of developing the module’s output.
  2. Enhances reusability of the module as all code is run in a separate environment, minimizing, even eliminating, the potential for variable conflict.
  3. Reduces time to load for length modules. For example, if a module is responsible for loading a dataset from disk or from the Internet, processing it, and returning it as a data frame, the module can do that once. The next lrequire() will return the cached copy of the data, forgoing all of the lengthy operations. This can be quite handy during the development phase of dashboard creation.