output markdown in r code chunk

2019-03-28 00:59发布

问题:

I have a R markdown file that I want to output rmarkdown from the script itself. For example, I would have the following simple code in an Rmd file.

---
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. There is a solution in an R script to generate markdown as per http://rmarkdown.rstudio.com/r_notebook_format.html. But I am trying to figure out how to do this in a Rmarkdown file. Any help appreciated. Thanks.

回答1:

Why build the header markup (either in markdown or HTML) manually? Try inline R expressions or some helper functions in pander (to generate markdown programatically):

---
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)
```


标签: r r-markdown