How to correctly specify relative path

rmarkdown
rstudio

#1

Hi,
I have started using R Projects for their self-contained utility. I'm wondering how I correctly specify paths - I would like to be able to share projects with others.

When I set a full path, a file is recognised, but when I try:

```{r load_scripts, include = FALSE}
source('./scripts/01_import.R')
```

I get the following error.

source('./scripts/01_import.R')
cannot open file './scripts/01_import.R': No such file or directoryError in file(filename, "r", encoding = encoding) :
cannot open the connection

The working directory is correct. I'm using R 3.5.0 and RStudio 1.1.453. Any ideas?
Thanks.


#2

I would recommend looking into the here package for maneuvering around a directory with relative ease.

More info here


#3

I would follow the recommendation of @raviolli77 using here package for file path in a RStudio project the portable way. If your script is in a folder script at the root of your RStudio Project: here::here("scripts", "01_import.R"). here is like file.path but always beggining at the root of your project, making it portable.

I just wanted to add to answer your question that by default a Rmd document is executed in the document directory, not the project directory. When using relative path, you need to be relative from the Rmd Document Directory.

Where is your document ? if in a subdirectory of project, it may be why the current relative path is not correct. if the Rmd is in ./document/myRmd.rmd you need to put the relative link ../scripts/01_import.R.

To deal with this, there is now an option in RStudio IDE, the the Knit menu about knit directory to change the execution folder for the document. You can choose project directory there.
image

At the end, here is the best solution though for portable RStudio Project.


#4

Thank you both for that information - I will have a look.


#5

In the Knit menu, it is easy to set the directory of the project or the file (@cderv shows a picture), or you can use the code to specify the path.

rstudioapi::getActiveProject() # project path
rstudioapi::getActiveDocumentContext()$path # file path

And you can use getwd() to check whether path is modified or not.