2

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.

Tlatwork
  • 1,445
  • 12
  • 35

1 Answers1

3

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

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
  • Thank you very much! If i may ask - do you have any hint on this related question: https://stackoverflow.com/questions/64942640/create-code-snippets-for-various-languages-in-rmardown-programmatically? If you dont find the time, thanks anyway!! – Tlatwork Nov 25 '20 at 16:16