Setting the default path for R Markdown files managed in subdirectories

Contents
  1. Default paths in R Markdown
  2. Solution
  3. Notes
  4. References

Default paths in R Markdown

When you keep R Markdown (.Rmd) files in subdirectories, specifying paths to external files can be confusing. By default, the working directory of an R chunk is the directory containing the .Rmd file. This means you need to keep in mind that any path referencing an external file inside a chunk is relative to the .Rmd file's directory.

Solution

If you manage your files with an RStudio project (.Rproj), adding knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file()) to the {r setup, include=FALSE} chunk sets the relative path for all chunks to be relative to the .Rproj file.

```{r setup, include=FALSE}
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
```Code language: PHP (php)

Notes

Unlike the usual way of changing the working directory with an .Rproj file, setwd() is not persistent in R Markdown—the working directory reverts to the default path in the next chunk. If you want to change the working directory for all chunks in R Markdown, setwd() will not do that.

It seems the default path is set relative to the .Rmd file because this offers an advantage, much like with .html files: as long as paths are relative to the .Rmd file, you can move the .Rmd file and the files it references anywhere freely.

Maintaining the file structure without depending on an .Rproj file has its advantages, though there are also times when it feels inconvenient. If you are using .Rmd files from the start, you generally have three options: (1) keep them in the same directory level as the .Rproj file, (2) configure the directory path as shown above, or (3) work with the default relative paths as they are. Any of these approaches works well as long as it fits your purpose.

Also, if you manage your work as a project, I recommend linking it with GitHub for version control. The initial setup may feel tedious, but I treat it as an investment in my future self. Please see the article below as well.

https://plaza.umin.ac.jp/shoei05/wp/index.php/2020/10/25/165/

References

  1. Riederer YX Christophe Dervieux, Emily. 16.6 The Working Directory for R Code Chunks | R Markdown Cookbook. Accessed November 1, 2020. https://bookdown.org/yihui/rmarkdown-cookbook/working-directory.html
  2. r – Setting work directory in knitr using opts_chunk$set(root.dir = …) doesn’t work. Stack Overflow. Accessed November 1, 2020. https://stackoverflow.com/questions/30237310/setting-work-directory-in-knitr-using-opts-chunksetroot-dir-doesnt-wor

English translation of the Japanese article.