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()?
setwd()is only bad after the computing has started. It is not inherently evil. On the contrary, it is always a good idea tosetwd()before everything else. After that, you assume everything is relative to the current working directory, which will make your life much easier. Setting theoutputargument ofknit()orknit2html()is almost always a bad idea. Well, I admit it is my headache as the package author. I'd encourage you to justsetwd("./docs/"); knit2html("report.Rmd"), and you getreport.html. - Yihui Xieopts_knit$set(base.dir = 'docs')fixes my problem. At first I tried settingbase.dirin a chunk option of the Rmd document. This didn't work. But settingbase.diroption in the R scriptknit_reports.Rdoes work and fixes my issue :-) - Paul Rougieux