Error with inserting picture in R Markdown

I'm trying to add the figure in my lecture note of RMarkdown.

I correctly located my file in the working directory of RStudio, but it is keep showing me error message.

Here is my working directory in RStudio.

and the code I typed in my RMarkdown is

Can anyone help on this? Thank you!

1 Like

Maybe put "./" in front of "figures/..."

If it still fails, you can try

```{r echo=FALSE, out.width="100%", fig.align='center'}
knitr::include_graphics("./figures/...")
```

2 Likes

+1 to RuReady! From a stackoverflow post:

The bookdown book does a great job of explaining that the best way to include images is by using include_graphics() . For example, a full width image can be printed with a caption below:


```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```

The reason this method is better than the pandoc approach ![your image](path/to/image) :

  • It automatically changes the command based on the output format (HTML/PDF/Word)
  • The same syntax can be used to the size of the plot ( fig.width ), the output width in the report ( out.width ), add captions ( fig.cap ) etc.
  • It uses the best graphical devices for the output. This means PDF images remain high resolution.
3 Likes

Thank you for your help @RuReady and @olyerickson. Now, I solved this problem.

I found out that there is working directly problem for this issue.

If I type getwd() in my RStudio console, then I got as below,

However, if I type getwd() in my RMarkdown as below, then I got as below,

The working directory is different in both output. That's why I was not able to load the figure. I don't know why it is showing different working directory. Maybe, the working directory in Rmarkdown is showing the where markdown file located ?

Thank you for your help!

Good to hear!

I forgot to mention that it is generally considered bad practice to use setwd() within R Notebooks; it reduces reproduciblity. Be careful!

2 Likes

yes you are right. By default, rmarkown execute in the directory it located. You can change that using the ezknitr :package: , setting knitr option opts_knit$set(root.dir = "<another directory") or using helpers package like the here to help you create automatically full path based on your current RStudio project, wherever your Rmd is.

Some ressources on the last options (the one I recommend)

Note that since RStudio 1.1, you can change the knitr directory in the IDE. See
https://blog.rstudio.com/2017/09/13/rstudio-v1.1---the-little-things/

3 Likes

Thank you for your recommendation! @cderv