Create code snippets by a loop in rmardown

Viewed 77

Similar to how to create a loop that includes both a code chunk and text with knitr in R i try to get text and a Code snippet created by a Loop.

Something along this:

---
title: Sample
output: html_document
params:
  test_data: list("x <- 2", "x <- 4")
---


for(nr in 1:3){
cat(paste0("## Heading ", nr))
```{r, results='asis', eval = FALSE, echo = TRUE}
params$test_data[[nr]]
```
}

Expected Output would be:

enter image description here

What i tried:

I tried to follow: https://stackoverflow.com/a/36381976/8538074. But printing "```" did not work for me.

1 Answers

You can make use of knitr hooks. Take the following MRE:

---
title: "Untitled"
output: html_document
params:
  test_data: c("x <- 2", "x <- 4")
---

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

```{r, results = 'asis', echo = F}
hook <- knitr::hooks_html()$source
opts <- knitr::opts_chunk$get()
chunks <- eval(parse(text = params$test_data))

for(nr in seq_along(chunks)){
  cat(paste0("## Heading ", nr, "\n"))
  cat(hook(chunks[nr], options = opts))
}
```

We get the default source hook and also the default chunk options. Then we get the test data, which is supplied as a string. Therefore we parse and evaluate that string. In the loop we simply call the source hook on each element of the test data. Here is the result:

enter image description here

Related