Search code examples
rr-markdownknitr

File not found with knitr::include_graphics in rmarkdown via RStudio when data and pdf-image present


I use win10 system and have the following file tree

  • C:\Users\xxx\Desktop\islr
    • C:\Users\xxx\Desktop\islr\data\Advertising.csv
    • C:\Users\xxx\Desktop\islr\fig\2-1.pdf

I have some .csv data sets and .pdf figures from https://www.statlearning.com/resources-first-edition; or you can test my demo.rmd using any .csv data and .pdf figure available at hand.

My demo.rmd reads as follows:

---
title: "TTT"
author: "aaa"
date: "2023"
output: beamer_presentation
---

```{r setup, include=FALSE}
knitr::opts_knit$set(root.dir=r"[C:\Users\xxx\Desktop\islr\data]")
knitr::opts_chunk$set(
  message = FALSE, 
  warning = FALSE,
  fig.align = "center"
)
library(knitr)
```

## data input

```{r}
ad = read.csv("Advertising.csv",row.names=1)
head(ad)
```

## image input

```{r}
getwd()
file.exists("../fig/2-1.pdf")
include_graphics('../fig/2-1.pdf')
```

When I test above demo.rmd, the data input part seems ok (you can test it by adding eval=F in the last code chunk), while the image input part gives error as

! LaTeX Error: File `../fig/2-1' not found.

However, commands

getwd()
file.exists("../fig/2-1.pdf")

show

[1] "C:/Users/xxx/Desktop/islr/data"
[1] TRUE

which makes me very confused! Did I neglect anything?


Solution

  • The issue is that the path set via root.dir sets the working directory for the code chunks. However, for images the root path is the path of the Rmd. See The working directory for R code chunks. One option which worked for me would be to use an absolute file path by wrapping your relative path in normalizePath() and setting rel_path=FALSE.

    ```
    ---
    title: "TTT"
    author: "aaa"
    date: "2023"
    output: beamer_presentation
    ---
    
    
    ```{r setup, include=FALSE}
    knitr::opts_knit$set(root.dir = r"[C:\Users\xxx\Desktop\islr\data]")
    knitr::opts_chunk$set(
      message = FALSE, 
      warning = FALSE,
      fig.align = "center"
    )
    library(knitr)
    ```
    
    ## data input
    
    ```{r}
    ad = read.csv("mtcars.csv",row.names=1)
    head(ad)
    ```
    
    ## image input
    
    ```{r}
    include_graphics(normalizePath("../fig/2-1.pdf"), rel_path = FALSE)
    ```
    

    enter image description here