'Sourcing files using relative paths

Let's say I have this project structure:

project/
├─ model-training/
│  ├─ h2o.R
├─ lib/
   ├─ formatter.R

in the h2o.R file, I would like to source the formatter.R using a relative path:

source('../lib/formatter.R')

rather than the usual way of specifying the full path:

source('lib/formatter.R')

and then being able to run it from the project folder:

R -f model-training/bigquery.R

but I get the error:

cannot open file '../lib/formatter.R': No such file or directory

I can get it to work by changing my working directory to the model-training. But really what I would like is the ability to run scripts from the project folder and that when I move the model-training and lib folders around (e.g. putting them into another folder), the source lines will not break by the virtue of them being relative. This is why I would like to use relative paths instead of absolute paths from the project folder.

(Moderators, I see that there are potentially similar questions asked previously on this forum, however they either don't include a full example, don't use source, accept "change the working directory" as the answer - in short, they don't answer my question.)

r


Solution 1:[1]

In the h2o.R file you could use:

currentDir = dirname(sys.frame(1)$ofile)
source(file.path(currentDir, "..","lib","formatter.R"))

This will only work if you source h2o.R.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 George Savva