Problems setting root.dir in knitr

RStudio sets the working directory to the project directory, but knitr sets the working directory to the .Rmd file directory. This creates issues when you are sourcing files relative to the project directory in your R markdown file. Specifically, knitr tells you it can’t find those files:

Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'home/sus/Documents/research_phd/analysis/phenodata_explore.R': No such file or directory

knitr has an option for dealing with this – root.dir – and Phil Mike Jones even gives a nice little knitr chunk example of using it.

But when I tried it, knitr kept failing to find my file.

```{r "setup", include=FALSE}
require("knitr")
opts_knit$set(root.dir = "~/Documents/research_phd/")
source('analysis/someanalysis.R')
```

It turns out I should have read the documentation more closely.

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.

Breaking it into two chunks separating the knitr configuration from the sourcing solved the problem.

```{r "knitr config", cache = FALSE, include=FALSE}
require("knitr")
opts_knit$set(root.dir = "~/Documents/research_phd/")
```

```{r, "setup", echo = FALSE}
source('analysis/someanalysis.R')
```
Tagged