knitr: How to set a figure path in knit2html without using setwd()?

knitr, r, r-markdown

Solution

Take a look at this page on chunk options. In particular, you have two options

- Use `fig.path` to set the plot directory relative to your working directory (OR)

- Use `base.dir` to set an absolute directory in which to save plots.

I think (2) might be a better solution in your context. Do not use `setwd()` in a `knitr` document since it is not good practice for keeping documents reproducible.

Problem

I work in a project folder let's say that its absolute path is: `/project`. `getwd()`tells me that I am in this project folder. All my file reading and writing are relative to this project root. `/project` has a subfolder `/project/docs/` In which there is a R Mardown file and an R script: `report.Rmd` contains: ```` ```{r } plot(cars) ``` ```` And `knit_reports.R` contains: ``` library(knitr) knit2html("./docs/report.Rmd", "./docs/report.html") ``` If I run `knit_reports.R`, a html page is generated but figures are not displayed on the page. The problem is that figures are stored under `/project/figures`. They are not visible for the html document generation. I'm looking for a way to tell knitr to store pictures under `/project/docs/figures` instead. Setting knitr options root.dir or base.dir in `report.Rmd` doesn't fix the problem, I tried `opts_knit$set(root.dir = "./docs")` or `opts_knit$set(base.dir = "/project/docs")`. However, if I change the working directory to `/project/docs`: ``` setwd("./docs/") knit2html("report.Rmd", "report.html") ``` A `/project/docs/figure` folder is created and figures appear on the html page. Many persons say it's bad to use setwd() in a script, because it messes up reproducibility. How can I tell knitr to place figures in my project subfolder without using setwd()?

Original source