2

knitr allows you to change the directory in which code chunks are evaluated by changing the root.dir option

```{r, setup, include=FALSE}
knitr::opts_knit$set(root.dir = '~/Project')
```

This can also be changed in the global options of RStudio

The directory options (with advantages and disadvantages) are well described in the R Markdown Cookbook: Chapter 16.6 The working directory for R code chunks.

I have the following file tree

├── Project
    ├── Fig
    │   └── Fig1.png
    └── Rmd
        └── Test.Rmd   

The R Markdown file Test.Rmd looks like this

---
title: "Title"
output: html_document
---

```{r, setup, include=FALSE}
knitr::opts_knit$set(root.dir = '~/Project')
```

Now include figure

```{r}
knitr::include_graphics('Fig/Fig1.png')
```

Rendering the R Markdown file like this will not include the figure.

There are many similar issues described

The suggested solution are

Option 1) use normalizePath() and set rel_path = FALSE

knitr::include_graphics(path = normalizePath('Fig/Fig1.png'), rel_path = FALSE)

Option 2) use path relative to Rmd file and set error = FALSE

knitr::include_graphics(path = "../Fig/Fig1.png", error = FALSE)

Option 3) use absolute path

knitr::include_graphics(path = '~/Project/Fig/Fig1.png', rel_path = FALSE)

Is there any better solution? Would it not be possible to fix knitr::include_graphics()?

retodomax
  • 434
  • 3
  • 14

0 Answers0