How to correctly specify relative path

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}

I get the following error.

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?

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

More info here


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.

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


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

1 Like

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.

I am sorry if this is a necro, I am attempting to use this solution to allow me to work on my file.R from my portable machine and from my home PC and finally be able to submit the project to the instructor and have it run successfully. Unfortunately for me when using the getwd() and now this here() function I get the same result from the console. That there is no file in that spot named my file, so I see what the results are giving me and both the getwd() and the here() commands return the same value in my users root directory. Thank you in advance for any clarification you can offer on using this here() command solution.