R: sourcing files using a relative path
After a discussion with @hadley on GitHub, I realized that my question goes against the common development patterns in R.
It seems that in R files that are sourced often assume that the working directory (getwd()
) is set to the directory they are in. To make this work, source
has a chdir
argument whose default value is FALSE
. When set to TRUE
, it will change the working directory to the directory of the file being sourced.
In summary:
Assume that
source
is always relative because the working directory of the file being sourced is set to the directory where the file is.To make this work, always set
chdir=T
when you source files from another directory, e.g.,source('lib/stats/big_stats.R', chdir=T)
.
For convenient sourcing of entire directories in a predictable way I wrote sourceDir
, which sources files in a directory in alphabetical order.
sourceDir <- function (path, pattern = "\\.[rR]$", env = NULL, chdir = TRUE)
{
files <- sort(dir(path, pattern, full.names = TRUE))
lapply(files, source, chdir = chdir)
}