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

And in the folder scripts
you have some *.Rmd
(*.rmd
) file or some *.R
(*.r
) script that you would like to knit/compile as HTML report (CTRL + SHIFT + K
from RStudio), then you have the options:
1) For the *.Rmd
file only, there is the option to define the path to your working directory at the top of the file (see the "Note" section in the help page of 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 the absolute path; though not encouraged if you will 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 fail on yours if you move my_project
)
```{r setup, include=FALSE}
knitr::opts_knit$set(root.dir = 'absolute/path/to/my_project/')
```
2) For both the *.R
script and the *.Rmd
file (though not encouraged in the "Note" section of the help page of knitr::knit
) - you can put at the top of your *.R
script or in the code chunk of 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 compiling (say when testing the script), it will not alter the usual getwd()
path since it cannot find the /scripts
pattern. When compiling to HTML it will edit the working directory path by deleting the /scripts
part from path/to/my_project/scripts
Both these options will allow you to keep on using relative paths like:
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 scritps before compiling them to HTML reports.