Setting work directory in knitr using opts_chunk$set(root.dir = ...) doesn't work

It is knitr::opts_knit instead of knitr::opts_chunk.


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.


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.

Tags:

R

Rstudio

Knitr