yindalon
yindalon

Reputation: 297

output markdown in r code chunk

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.

Upvotes: 16

Views: 7234

Answers (2)

Claudiu Papasteri
Claudiu Papasteri

Reputation: 2619

I searched for a good answer for this for some time after using cat("## Heading") inside results='asis' code chucks. 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. We have many cases when we want to output the heading along with results that should be wrapped in markup (e.g. a kable table that renders to a html table).

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.

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

enter image description here

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.

Upvotes: 6

daroczig
daroczig

Reputation: 28682

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

Upvotes: 20

Related Questions