0

Can one use an R Markdown chunk loop to show multiple graphics files (e.g., PNG) consecutively (one above the other) in HTML output? This loop would identify the files in a vector, such as via list.files().

I have experimented with no avail to uses of writeLines("\n"), cat('\r\n\r\n') per this SO.

This R Markdown code (formatted below but link is .Rmd) is a reproducible example with an attempt using writeLines("\n") and cat('\r\n\r\n'). Please note this copies 5 R logo PNG (only 12kb) file copies into your working directory.

---
title: "Stack Overflow Consecutive PNG"
author: "Rick Pack"
date: "11/20/2019"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Copy a PNG file as multiple files

```{r png_copy, echo=FALSE}
for (q in 1:5) {
 file.copy(list.files(system.file("img", package = "png"), 
                      full.names = TRUE),
           getwd())
 file.rename("Rlogo.png", paste0("Rlogo_",q,".png"))
}
```

# Only one R logo shown instead of the five available
```{r png_show, echo=FALSE}
library(png)
# Providing the folder so you can delete the png files
# created above
print(getwd())
 all_img <- list.files(full.names = TRUE)[grepl(
     "Rlogo", list.files())]
 for (j in 1:length(all_img)) {  
 grid::grid.raster(readPNG(all_img[j]))
writeLines("\n")
cat('\r\n\r\n')  
cat("\n\n\\pagebreak\n")
 }
```

Showing only one PNG file appeared

Rick Pack
  • 1,044
  • 10
  • 20

1 Answers1

3

You can use R Markdown syntax within the for loop instead of the png package. Given you have the images in the same directory as your Rmd, the following should work:

```{r, results = "asis"}
filelist <- c("Rlogo_1", "Rlogo_2", "Rlogo_3")

for(i in filelist) {
    cat(paste0("![](", i, ".png)"), "\n")
    cat("\n\n\\pagebreak\n")
}
```

Output: enter image description here See this related question for more info: Insert images using knitr::include_graphics in a for loop

joshpk
  • 729
  • 4
  • 11
  • That solution printed strings like []./Rlogo_1.PNG but the link you provided gave the solution: just set the argument of knitr::include_graphics() to the vector containing the full paths to the image files. In my example: knitr::include_graphics(all_img) would appear in a chunk. Thanks! – Rick Pack Nov 22 '19 at 20:35
  • It will print strings in the in-line output, but when you knit the document it should embed the images. – joshpk Nov 22 '19 at 21:13
  • that was what I meant: the HTML showed only the strings. – Rick Pack Nov 22 '19 at 21:41