This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Rmarkdown report from multiple images

Hi, I want to make an R markdown report and I want to include multiple images from a local folder (not from running code) into the report. However, since there are many images I prefer to use some form of automation (regex, etc) to include all the .png images in a folder. I was not successful so far and I couldn't find a workaround to that. Does anyone have any experience how to do that? Thanks!

markdown r pandoc knitr

2 answers

You need to do as suggested by Zaag to get the image file names but you also need some special care in order to include the images. One is to use results = 'asis' in the chunk options. The other is to create the ![image_label](image_filename) entries. This is an example that worked for me:

```{r, results='asis'}
files <- list.files(path = "Desktop", pattern = "png", full.names = TRUE)
for (f in files) {
  cat(paste0("![image_label](", f, ")\n"))
  }
```

Thanks ddiez and zaag. It was a smart solution. Very big help!

Thank you so much for this solution. I've been searching for something like this for hours.

Instead of a newline, I've added a page break between each image. Now, is it possible to center these images vertically on the page?

img_list <- list.files( path = '/path/to/imgfolder/',  pattern = '*.png$'")

This gives you a list (img_list) with all the filesin the folder /path/to/imgfolder/ that end ($) in .png

Thanks! Maybe I was not clear enough. Making the list is not a problem. The problem is that I can't make the list object work in insert image command.

```{r}
files <- list.files(path="/path/to/files", pattern="*.png$", full.names=T, recursive=FALSE)
```
![](files)

It doesn't work this way since, ![](path) should be out of {r} signs and I cannot run a loop without having that.

See my answer for an example on how to get this.

As ddiez explains, I'd use something like this:

```{r, results='asis'}
img_list <- list.files( path = 'D:/img/',  pattern = '*.png$')

for (img in img_list){
  cat(paste("![img](/path/to/files/", img, sep='' ) , ")\n")

  }
cat("  \n")
```

Log in to answer this question.