Scoping during package development

rstudio

#1

In accordance to the instructions on how to develop packages available under http://r-pkgs.had.co.nz/ and the devtools package, I put the R source files of my package in the folder R/.

If I need to call a function from another file in a particular file, then I need to call source("file_with_function.R") in this file.

After the package has been build (R CMD build my_package), then the call to source("file_with_function.R") is as far as I know no longer necessary.

Can I avoid the source() calls during development without getting error messages that objects/functions in other files don't exist?


#2

You should definitely avoid source()ing files. In fact, it's one of the advantages of having everything in a package. In the book the proposed workflow is as follows:

R code workflow
The first practical advantage to using a package is that it’s easy to re-load your code. You can either run devtools::load_all(), or in RStudio press Ctrl/Cmd + Shift + L, which also saves all open files, saving you a keystroke.
This keyboard shortcut leads to a fluid development workflow:

  1. Edit an R file.
  2. Press Ctrl/Cmd + Shift + L.
  3. Explore the code in the console.
  4. Rinse and repeat.

Congratulations! You’ve learned your first package development workflow. Even if you learn nothing else from this book, you’ll have gained a useful workflow for editing and reloading R code.