The following works for me - if you have your project (say a directory called my_project ), organized something like this:

And in the scripts folder you have some *.Rmd ( *.rmd ) or *.R ( *.r ) script that you want to link / compile as an HTML report ( CTRL + SHIFT + K from RStudio), then you have there are options:
- 1) Only for the
*.Rmd file, it is possible to determine the path to your working directory at the top of the file (see the note in the help knitr::knit ):
'''{r setup, include=FALSE} knitr::opts_knit$set(root.dir = '../') # Or use multiple '../' if needed; # One '../' means go one level up towards the root, # here, moving from 'scripts' folder to the root 'my_project' '''
or use an absolute path; although this is not recommended if you share your directory / repository with colleagues (on Windows, something like C: /my/absolute/path/to/my_project will not work on any other computer and will also not work on your if you move my_project )
'''{r setup, include=FALSE} knitr::opts_knit$set(root.dir = 'absolute/path/to/my_project/') '''
- 2) As for the
*.R script and the *.Rmd file (although this is not recommended in the knitr::knit help knitr::knit ) - you can put it at the beginning of your *.R script or in the code fragment your *.Rmd file ( where you read some data) something like:
setwd(gsub(pattern = '/scripts', replacement = '', x = getwd()))
If you run / execute the *.R script without compilation (say, when testing the script), it will not change the usual getwd() because it cannot find the /scripts template. When compiling in HTML, it will edit the path to the working directory, removing the /scripts part from path/to/my_project/scripts
Both of these options allow you to use relative paths, such as:
read.csv('data/my_data.csv')
avoiding something like:
read.csv('../data/my_data.csv')
which can be tricky if you want to test your scripts before compiling them into HTML reports.
Valentin
source share