My R project is structured like a package with directories /R
, /vignettes
, /data
etc. In one of my Rmd docs in /vignettes
Where you have an R project with nested subfolders, so that the .Rproj and .Rmd files are located in different folders, you can use the command rprojroot::find_rstudio_root_file()
to find and set the working directory to the Project's main folder during Kniting (instead of the folder containing the rMarkdown code file).
So at a minimum use the following:
```{r setup}
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
```
inside the setup
chunk.
See also Automatically finding the path of current R project in R Studio and https://support.rstudio.com/hc/en-us/community/posts/220826588-Working-directory-in-R-Notebooks.
Some details on implementation of setting work directory by root.dir =
.
Although there already are some awesome answers by Yihui and Tommy. I still got stuck in setting work directory. So I am trying to make a complete answer here.
Knitr’s settings must be set in a chunk before any chunks which rely on those settings to be active. It is recommended to create a knit configuration chunk as the first chunk in a script with cache = FALSE and include = FALSE options set. This chunk must not contain any commands which expect the settings in the configuration chunk to be in effect at the time of execution.
In my case, the .Rproj
and .Rmd
files are located in the same folder.
```{r setup, include=FALSE, cache = FALSE}
require("knitr")
## setting working directory
opts_knit$set(root.dir = "~/Documents/R/Example")
```
As Yihui has pointed out in his answer the mistake was simply that I used opts_chunk$set()
instead of opts_knit$set()
.
However it might be worth noting that the change of the working directory affects not the current but only the next chunk. So e. g. if you want to load data relative to the new working directory do that in the following chunk.
It is knitr::opts_knit instead of knitr::opts_chunk
.
For me knitr::opts_knit$set
worked with root.dir
but didn't work with echo = FALSE
while
knitr::opts_chunk$set
didn't work with root.dir
but did work with echo = FALSE
Therefore,
I used both options in the setup chunk:
```{r settings, include = FALSE}
knitr::opts_chunk$set(echo = FALSE
, comment = NA
, warning = FALSE
, error = FALSE
, message = FALSE
, tidy = TRUE)
knitr::opts_knit$set(root.dir = 'C:/...')
```