Domanda

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()?

È stato utile?

Soluzione

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

  1. Use fig.path to set the plot directory relative to your working directory (OR)
  2. 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.

Altri suggerimenti

Ramnath's answer to set base.dir was the good answer. But at first I thought the option should be set in Rmd chunks and this didn't work. The option should be set in the R script. This is a question of scope I guess.

So in my example above knit_reports.R should contains:

library(knitr)
opts_knit$set(base.dir = 'docs') # Change the base dir where to save figures
knit2html("./docs/report.Rmd", "./docs/report.html")

I would like to add, that you may run into problems, if you specify a different output-directory in knit2html, as the figure-folder is saved into the original directory. Then, at least in my experience, the html file will not contain your plots. So: as mentioned elsewhere. Try not to change the output directory

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top