Chapter 6. R Code
The first principle of making a package is that all R code goes in the R/ directory. In this chapter, you’ll learn about organizing your functions into files, maintaining a consistent style, and recognizing the stricter requirements for functions in a package (versus in a script). We’ll also remind you of the fundamental workflows for test-driving and formally checking an in-development package: load_all()
, test()
, and check()
.
Organize Functions Into Files
The only hard rule is that your package must store its function definitions in R scripts, i.e., files with extension .R, that live in the R/ directory.1 However, a few more conventions can make the source code of your package easier to navigate and relieve you of re-answering “How should I name this?” each time you create a new file. The Tidyverse Style Guide offers some general advice about filenames and also advice that specifically applies to files in a package. We expand on this here.
The filename should be meaningful and convey which functions are defined within. While you’re free to arrange functions into files as you wish, the two extremes are bad: don’t put all functions into one file and don’t put each function into its own separate file. This advice should inform your general policy, but there are exceptions to every rule. If a specific function is very large or has lots of documentation, it can make sense to give it its own file, named after the function. More often, a single .R file will contain ...
Get R Packages, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.