Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert images using knitr::include_graphics in a for loop

Tags:

r

knitr

```{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 = ""))
}
```
like image 628
Adrian Avatar asked Jul 10 '18 15:07

Adrian


2 Answers

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)")

like image 169
pogibas Avatar answered Nov 16 '22 04:11

pogibas


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)

```
like image 21
Tung Avatar answered Nov 16 '22 05:11

Tung