在 r 代码块中输出 markdown

output markdown in r code chunk

我有一个 R markdown 文件,我想从脚本本身输出 rmarkdown。例如,我会在 Rmd 文件中包含以下简单代码。

---
title: "test"
author: "johndoe"
date: "September 5, 2015"
output: html_document
---

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

```{r cars}
paste("## This is a Heading in Code")
summary(cars)
```

我希望 "This is a Heading in Code" 在 rmarkdown 中呈现。 R 脚本中有一个解决方案可以根据 http://rmarkdown.rstudio.com/r_notebook_format.html 生成 markdown。但我想弄清楚如何在 Rmarkdown 文件中执行此操作。任何帮助表示赞赏。谢谢

为什么要手动构建 header 标记(在 markdown 或 HTML 中)?在 pander 中尝试内联 R 表达式或一些辅助函数(以编程方式生成降价):

---
title: "test"
author: "johndoe"
date: "September 5, 2015"
output: html_document
---

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

## `r 'This is a Heading in Code'`

```{r title, results='asis'}
library(pander)
pandoc.header("This is a Heading in Code", level = 2)
```

```{r cars, results='asis'}
summary(cars)
```

results='asis' 代码卡盘中使用 cat("## Heading") 之后,我为此搜索了一段时间的好答案。我看到很多人对代码块中的 results='asis' 设置不满意,因为它将代码块的 all 结果设置为不包含在代码标记块中。在很多情况下,我们想要输出标题以及应包含在标记中的结果(例如,呈现为 html table 的 kable table)。

这是我通过简单地将“asis”属性指定给文本 object 和 knitr::asis_output 并将代码块保持在默认 'markup' 设置中找到的解决方案。

---
title: "test"
author: "johndoe"
date: "September 5, 2015"
output: html_document
---

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

```{r cars}
knitr::asis_output("## This is a Heading in Code")
summary(cars)
knitr::kable(summary(cars))
``` 

不幸的是,目前 knitr::asis_output 仅在 top-level R 表达式中有效,在另一个表达式中调用它时将无效,例如 for-loop.