1

Im new to Rmarkdown and I would like to create dynamic reports where every report section is generated from a template (child) document. Each section will then start with a newpage in the rendered pdf.

My approach is currently based on this post which shows how to generate dynamically text in the child (which works), however I am not able to transfer the contents of the loop into a R-Codeblock, probably because the params are not well defined in the way that I tried to do it.

This is how my parent document looks like:

---
title: "Dynamic RMarkdown"
output: pdf_document
---


```{r setup, include=FALSE}
library("knitr")
options(knitr.duplicate.label = "allow")
```

# Automate Chunks of Analysis in R Markdown 
Blahblah Blabla
\newpage

```{r run-numeric-md, include=FALSE}
out = NULL
for (i in as.character(unique(iris$Species))) {
  out = c(out, knit_expand('template.Rmd'))
  params <- list(species = i)
}
```

`r paste(knit(text = out), collapse = '\n')`

and this is how the child looks like

---
title: "template"
output: html_document
params:
  species: NA
---

# This is the reporting section of Species {{i}}

This is a plot of Sepal length and width based on species {{i}}.

```{r plot2}

paste(params$species)
# plot doesnt work work
# plot(iris$Sepal.Length[iris$Species=={{i}}],
#     iris$Sepal.Width[iris$Species=={{i}}]
#     )

```
\newpage

To my understanding the parameter that is actually passed is the last species from the dataset generated in the loop but I'm not sure why the plot would't work then. Can anybody help me out on how to fix this issue?

Joschi
  • 2,941
  • 9
  • 28
  • 36

1 Answers1

4

Ok. No need to go through params. The solution was simply to put i between brackets AND parenthesis in the child-document.

Parent:

---
title: "Dynamic RMarkdown"
output: pdf_document
---


```{r setup, include=FALSE}
library("knitr")
options(knitr.duplicate.label = "allow")
```

# Automate Chunks of Analysis in R Markdown 
Blahblah Blahblah Main text before individual sections
\newpage

```{r run-numeric-md, include=FALSE}
out = NULL
for (i in as.character(unique(iris$Species))) {
  out = c(out, knit_expand('template.Rmd'))
}
```

`r paste(knit(text = out), collapse = '\n')`

Child

---
title: "template"
output: html_document
---

# This is the reporting page of Species {{i}}
This is a plot of Sepal length and width based on species {{i}}.
```{r plot2}
paste("This will be a plot of Sepal Length and Witdh from", '{{i}}')

plot(iris$Sepal.Length[iris$Species=='{{i}}'],
     iris$Sepal.Width[iris$Species=='{{i}}']
     )
```
\newpage

Original solution found here.

Joschi
  • 2,941
  • 9
  • 28
  • 36