在 purrr 中创建 RMarkdown headers 和代码块

Create RMarkdown headers and code chunks in purrr

以下.Rmd是我认为应该产生我正在寻找的东西:

---
title: "Untitled"
date: "10/9/2021"
output: html_document
---

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

full_var <- function(var) {
  cat("### `", var, "` {-} \n")
  cat("```{r}", "\n")
  cat("print('test')", "\n")
  cat("```", "\n")
}

vars <- c("1", "2", "3")
```

```{r results = "asis"}
purrr::walk(vars, full_var)
```

相反,它看起来像:

为什么 print('test') 没有被评估,而是作为代码块呈现?

解决方案

如果您呈现您的代码 以及 运行 在 result='asis' 块中整合您的代码的结果,我认为您可以管理您的代码再之后。您可以通过利用 knitrknit() 功能来做到这一点,如下所示:

---
title: "Untitled"
date: "10/9/2021"
output: html_document
---

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

full_var <- function(var) {
  
  # Define the code to be run
  my_code <- "print('test')"
  
  # Print the code itself, surrounded by chunk formatting
  cat("### `", var, "` {-} \n")
  cat("```{r}", "\n")
  cat(my_code, "\n")
  cat("``` \n")
  
  # Use knitr to render the results of running the code.
  # NB, the use of Sys.time() here is to create unique chunk headers,
  # which is required by knitr. You may want to reconsider this approach.
  cat(knitr::knit(
    text = sprintf("```{r %s}\n%s\n```\n",  Sys.time(), my_code), 
    quiet = TRUE
  ))
}

vars <- c("1", "2", "3")
```

```{r results = "asis"}
purrr::walk(vars, full_var)
```

这会产生如下输出:

详细信息:knitr 的工作原理

knitr renders an R Markdown file 它在以下阶段这样做:

  1. knitr 从您的原始 .Rmd 生成一个普通的降价文件。这是使用 yaml header 和块选项之类的东西的时候,而且至关重要的是 当你的 R 代码得到 运行
  2. pandoc 将 markdown 文件转换为最终输出。此处具体发生的情况取决于您使用的输出格式。

使用results='asis'

块选项 results = 'asis' 只是更改中间 markdown 脚本在呈现过程中的外观。例如,

```{r}
cat("print('# Header')")
```

将呈现为 markdown 如下:(注意这里的缩进意味着这是根据 markdown 语法的代码):

    ## # print('# Header')

然而,如果使用 results = 'asis',您将获得降价

print('# Header')

要意识到的关键是,"print('# Header')"虽然是有效的R代码,但它只出现在流程中的2阶段,毕竟是R代码已经 运行.

take-home 消息

不幸的是,你不能期望 results='asis' 输出 R 代码 然后 运行 它 ,因为 knitr 已经完成 运行到此为止你的 R 代码。

实现目标的另一种方式:

---
  title: "Untitled"
date: "10/9/2021"
output: html_document
---

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

full_var <- function(var) {
  cat("### `", var, "` {-} \n")
  cat("```{r}", "\n")
  cat(eval(parse(text = "print('test')")), "\n")
  cat("```", "\n")
}

vars <- c("1", "2", "3")
```

```{r results = "asis"}
purrr::walk(vars, full_var)
```