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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! If i may ask - do you have any hint on this related question: stackoverflow.com/questions/64942640/…? If you dont find the time, thanks anyway!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.