R: source() and path to source files

If you are distributing a script to colleagues, you should really not be writing a script that sources other scripts. What if you want to rename or move functions.R in the future? What if you need to modify a function in functions.R, but wrapper.R relies on the older version of that function? It's a flimsy solution that will cause headache. I would recommend either of the following instead.

  1. Put everything needed into a single, self-contained script and distribute that.

  2. If you really want to separate code into different files, write a package. Might sound like overkill, but packages can actually be very simple and lightweight. In the simplest form a package is just a directory with a DESCRIPTION and NAMESPACE file along with an R/ directory. Hadley breaks this down nicely: https://r-pkgs.org/whole-game.html.


You can do this using the here package. It uses the "current working directory at the time when the package is loaded". In other words, the directory you start your R session from.

In your case the code would be:

source(here::here('functions.R'))

This will work even if the wrapper script wrapper.R is in a different directory in the project.

If functions.R is in a subdirectory of the project, just add it to the call to here(), to complete the relative path:

source(here::here('subdirectory', 'functions.R'))