21
```{r}
knitr::include_graphics(path = "~/Desktop/R/Files/apple.jpg/")
```

The above code chunk works fine. However, when I create a for loop, knitr::include_graphics does not appear to be working.

```{r}
fruits <- c("apple", "banana", "grape")
for(i in fruits){
  knitr::include_graphics(path = paste("~/Desktop/R/Files/", i, ".jpg", sep = ""))
}
```
pogibas
  • 27,303
  • 19
  • 84
  • 117
Adrian
  • 9,229
  • 24
  • 74
  • 132

2 Answers2

22

This is a known issue knitr include_graphics doesn't work in loop #1260.

A workaround is to generate paths to images within a for loop and cat them. To show final result result = "asis" is required.

```{r, results = "asis"}
fruits <- c("apple", "banana", "grape")
for(i in fruits) {
    cat(paste0("![](", "~/Desktop/R/Files/", i, ".jpg)"), "\n")
}
```

Here each iteration generates markdown path to graphics (eg, "![](~/Desktop/R/Files/apple.jpg)")

pogibas
  • 27,303
  • 19
  • 84
  • 117
  • Thanks @PoGibas. Using `print(paste0("![](", "~/Desktop/R/Files/", i, ".jpg)"))` worked, but I'm seeing `[1]"` and `"` around my image (i.e. I seem to be printing an extra set of quotation marks). – Adrian Jul 10 '18 at 17:44
17

include_graphics() has to be used in top-level R expressions as Yihui stated here

My workaround is this:

```{r out.width = "90%", echo=FALSE, fig.align='center'}
files <- list.files(path = paste0('../', myImgPath), 
                    pattern = "^IMG(.*).jpg$",
                    full.names = TRUE)

knitr::include_graphics(files)

```
Tung
  • 26,371
  • 7
  • 91
  • 115
  • 2
    This solution works also with `files <- dir("path/to/files/", pattern = "pattern.*jpg$", full.names = TRUE)` instead of `list.files` too. – PavoDive Nov 14 '20 at 12:34
  • 1
    A note about _why_ this works. `list.files` outputs a vector of class character, which is what `include_graphics` expects. So files could be any character vector of file paths, or a `list` converted to `as.character(list_of_paths)`. _e.g._ ```{r} fruits <- c("apple", "banana", "grape"); files <- lapply(X = fruits, FUN = function(fr){ file.path("~/Desktop/R/Files/",paste0(fr, ".jpg") ) } ) ; knitr::include_graphics( as.character(files) ) ``` – Foztarz Mar 16 '22 at 14:40