1

I'm automating a presentation and want to create a slide for each image in a directory (the image filenames are all .png files with three-character names).

This works as desired to test that the slide with title and image will render:

```{r, results="asis", out.width="900px"}
plot_files <- list.files(paste0(mydir, "/plots"))
i <- 1
cat("\n\n##", substr(plot_files[i], 1, 3), "\n\n", sep="")
knitr::include_graphics(paste0(dir, "/plots/", plot_files[i]))
```

But when I wrap the above into a for loop...

```{r, results="asis", out.width="900px"}
plot_files <- list.files(paste0(mydir, "/plots"))
for (i in 1:length(plot_files)) {
  cat("\n\n##", substr(plot_files[i], 1, 3), "\n\n", sep="")
  knitr::include_graphics(paste0(dir, "/plots/", plot_files[i]))
}
```

...each of the slides is correctly generated with the title, but the images no longer render. Any ideas why wrapping the code in the loop would cause the image rendering to fail?

Bryce F
  • 101
  • 1
  • 1
  • 5
  • 1
    After searching more through knitr documentation, I see this is a known issue: https://github.com/yihui/knitr/issues/1260; knitr can only evaluate top-level expressions. – Bryce F Jan 09 '18 at 21:47

1 Answers1

1

Instead of knitr::include_graphics(), I think you can use the (Pandoc) Markdown syntax for images, e.g.

cat('![](', paste0(dir, "/plots/", plot_files[i]), '){width=900px}\n\n', sep = '')
Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • Thanks...but none of the various attempts I made to modify the image size when using this `![](path)` format would do anything to change the image size. – Bryce F Jan 11 '18 at 20:56
  • Whether modifications to image size were given in the chunk header or in the loop itself made no difference. What ended up working was the html itself: `cat("", sep="")` – Bryce F Jan 11 '18 at 21:02
  • Note I had `{width=900px}` in my answer. It should work with a reasonably recent version of Pandoc. Check `rmarkdown::pandoc_version()` if you are not using the latest version of RStudio. More info: http://pandoc.org/MANUAL.html#images – Yihui Xie Jan 12 '18 at 02:36