Create code snippets by a loop in rmardown

会有一股神秘感。 提交于 2021-01-01 04:22:09

问题


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:

What i tried:

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


回答1:


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:



来源:https://stackoverflow.com/questions/64848847/create-code-snippets-by-a-loop-in-rmardown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!