[英]output markdown in r code chunk
I have a R markdown file that I want to output rmarkdown from the script itself.我有一个 R markdown 文件,我想从脚本本身输出 rmarkdown。 For example, I would have the following simple code in an Rmd file.
例如,我将在 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)
```
I want "This is a Heading in Code" to render in rmarkdown.我希望“这是代码中的标题”在 rmarkdown 中呈现。 There is a solution in an R script to generate markdown as per http://rmarkdown.rstudio.com/r_notebook_format.html .
R 脚本中有一个解决方案可以根据http://rmarkdown.rstudio.com/r_notebook_format.html生成降价。 But I am trying to figure out how to do this in a Rmarkdown file.
但我想弄清楚如何在 Rmarkdown 文件中做到这一点。 Any help appreciated.
任何帮助表示赞赏。 Thanks.
谢谢。
Why build the header markup (either in markdown or HTML) manually?为什么要手动构建标题标记(在 Markdown 或 HTML 中)? Try inline R expressions or some helper functions in
pander
(to generate markdown programatically):在
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)
```
I searched for a good answer for this for some time after using cat("## Heading")
inside results='asis'
code chucks.在
results='asis'
代码夹中使用cat("## Heading")
后,我为此搜索了一段时间的好答案。 I have seen many people dissatisfied by the results='asis'
setting in the code chunk because it sets all results of the code chunk to not be wrapped in a code markup block.我看到很多人对代码块中的
results='asis'
设置不满意,因为它将代码块的所有结果设置为不包含在代码标记块中。 We have many cases when we want to output the heading along with results that should be wrapped in markup (eg a kable table that renders to a html table).当我们想要输出标题以及应该包含在标记中的结果(例如呈现为 html 表的 kable 表)时,我们有很多情况。
Here is the solution I found by simply specifying the "asis" attribute to the text object with knitr::asis_output
and keeping the code chunk in the default 'markup'
setting.这是我通过简单地使用
knitr::asis_output
将“asis”属性指定给文本对象并将代码块保持在默认的'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))
```
Unfortunately, at the current time knitr::asis_output
only works in top-level R expressions, and it will not work when it is called inside another expression, such as a for-loop.不幸的是,目前
knitr::asis_output
仅适用于顶级 R 表达式,并且在其他表达式(例如 for 循环)中调用时将无法使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.