plots after dynamic sections using R Markdown pander, knitr and pandoc

173 Views Asked by At

I use this rmd:

---
title: "Some Title"
author: "Some Author"
date: "`r format(Sys.time(), '%d-%m-%Y')`" 
---

## A function that generates sections

```{r setup, include = FALSE}
library(pander)

create_section <- function() {

   # Inserts "## Title (auto)"
   pander::pandoc.header('Title (auto)', level = 2)

   # Section contents
   # e.g. a random plot
   plot(sample(1000, 10))

   # a list, formatted as Markdown
   # adding also empty lines, to be sure that this is valid Markdown
   pander::pandoc.p('')
   pander::pandoc.list(letters[1:3])
   pander::pandoc.p('')
}
```

## Generate sections

```{r, results='asis', echo=FALSE}
n_sections <- 3

for (i in seq(n_sections)) {
   create_section()
}
```

and then:

library(knitr);
library(rmarkdown);

setwd("C:/bla")

knit('test_md.Rmd')
rmarkdown::pandoc_convert("test_md.md", to = "pdf", output = "test_pdf.pdf")

This kind of works but the plots are all rendered after the sections:

enter image description here

Each section should contain the plot. Any ideas? Thanks!

PS:

Wrapping:

plot(sample(1000, 10))

in print:

print(plot(sample(1000, 10)))

forces output to be produced. Unfortunately, NULL is also printed underneath the plot.

1

There are 1 best solutions below

1
Daniel_j_iii On

Could you just add pdf_document in the YAML and then generate the PDF by knitting?

---
title: "Some Title"
author: "Some Author"
date: "`r format(Sys.time(), '%d-%m-%Y')`" 
output: pdf_document
---

enter image description here

I was able to get the same result you described when running the rmarkdown::pandoc_convert() on the .md file, all the plots at the end of the .PDF file.