49

My R project is structured like a package with directories /R, /vignettes, /data etc. In one of my Rmd docs in /vignettes I source a script which in located in /R. Inside this script I use read.csv() to load a file located in inst/extdata/.
The problem now is that by default the working directory inside the Rmd file is the directory where the file is located. Let's call it /Users/Me/Docs/Proj/vignettes. However in order for the R script to run the working directory needs to be the project's main directory (/Users/Me/Docs/Proj).
I tried to change the working directory in the Rmd file using knitr::opts_chunk$set(root.dir = normalizePath(".."). However apparently this doesn't change the working directory since if I call getwd() after it the output is still /Users/Me/Docs/Proj/vignettes whereas knitr::chunk_opts$get("root_dir") returns /Users/Me/Docs/Proj.

Here is a minimal example Rmd file:

```{r}
getwd()  # returns 'Users/Me/Docs/Proj/vignettes'
knitr::opts_chunk$set(root.dir = normalizePath(".."))  # should change the working directory to 'Users/Me/Docs/Proj'
getwd()  # again returns 'Users/Me/Docs/Proj/vignettes'
knitr::opts_chunk$get("root.dir")  # returns 'Users/Me/Docs/Proj'
```

I am using RStudio Version 0.99.435. Here is my session Info:

R version 3.2.0 (2015-04-16)  
Platform: x86_64-apple-darwin14.3.0 (64-bit)  
Running under: OS X 10.10.3 (Yosemite)  

locale:
[1] de_DE.UTF-8/de_DE.UTF-8/de_DE.UTF-8/C/de_DE.UTF-8/de_DE.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] htmltools_0.2.6 tools_3.2.0     yaml_2.1.13     rmarkdown_0.6.1 digest_0.6.8   

Any help is kindly appreciated. If you need more info post a comment to the question. Thanks in advance!

Thomas Neitmann
  • 2,552
  • 1
  • 16
  • 31
  • Why not just use `setwd()`? – Stibu May 14 '15 at 19:09
  • 7
    From the documentation of `knitr::knit`: "It is not recommended to change the working directory via ‘setwd()’ in a code chunk, because it may lead to terrible consequences (e.g. figure and cache files may be written to wrong places). If you do use ‘setwd()’, please note that ‘knitr’ will always restore the working directory to the original one." – Thomas Neitmann May 17 '15 at 19:25

7 Answers7

45

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

JWilliman
  • 3,558
  • 32
  • 36
42

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

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • 3
    This works in RStudio 1.0.143 for linux, but ONLY in the ```{r setup}...``` chunk. Just calling it ```{r initialization}...``` breaks it. – mightypile Apr 26 '17 at 11:15
23

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.

Thomas Neitmann
  • 2,552
  • 1
  • 16
  • 31
10

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.

  1. From knitr documentation:

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.

  1. My code example:

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")
```
Guannan Shen
  • 649
  • 8
  • 12
  • I had the same problem in setting working directory in a notebook (RStudio 1.2.1335, R 3.5.3), despite of the answers of @Yihui and @Tommy, due to the command `getwd()` inside of the _setup-chunk_. Thank you @Guannan for clarifying the solution! – Gregor Kvas May 22 '20 at 10:47
3

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:/...')

```
  • If you look here https://yihui.org/knitr/options/#package-options you'll find two blocks in the table of contents called "Chunk options" and "Package options". I've just realized that they are about your confusion. I had the same. – Sergey Skripko May 26 '22 at 12:49
0

I could not get knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file()) in the setup chunk to work with knitr::include_graphics (works fine for source() and load()) when the .Rmd file is located in a subdirectory upstream of other files. If you have the same problem, try:

library(here)
knitr::include_graphics(here("figs/figure.png"))

You could obviously use ../ too in these cases, but then the paths would not work directly in the console while debugging.

Source for the solution: https://community.rstudio.com/t/knittr-include-graphics-image-png-cannot-find-files/82959/2

Mikko
  • 7,530
  • 8
  • 55
  • 92
0

the below chunk is in need as the first one in a Rmd script.

{r setup, include=FALSE, cache = FALSE}
knitr::opts_knit$set(
  root.dir = rprojroot::find_rstudio_root_file()
  )

but, it does not work once in while. And i find it's possible caused by chunk output setting. Chunk output inline and chunk output in console are different. Make sure Chunk output inline and setup chunk will work.