Reputation: 4537
I would like to write an R Markdown document which presents code examples of how to write an R Markdown document. For example, I want to show in the document how to render text as bold.
`**this is bold**` will render 'this is bold' with bold text, i.e. **this is bold**
That works fine, the ` render the text within as code. However, I can't figure out how to get a code chunk to display properly. e.g.
```{markdown, eval=FALSE}
```{r}
x = rnorm(1)
```
```
This doesn't work because markdown isn't a supported language. I can't enclose the r code block in ` because I need that symbol to mark the beginning of the code chunk and it only works inline.
I can do some hoop jumping by actually using R
```{r, echo="FALSE"}
o = "```{r}\nx=sample(1)\n```\n"
cat(o)
```
which renders as
## ```{r}
## x=sample(1)
## ```
But this is more complicated for me writing the document and the code it generates doesn't allow for simple copy/paste.
Is there a native way to render as code the markdown necessary to create the R code block?
Upvotes: 4
Views: 899
Reputation: 15369
You can use the experimental knitrhooks package, which adds the chunk option chunk_head
to enable us to keep the header. The package is in development on GitHub here.
To install the package, use the command devtools::install_github("nathaneastwood/knitrhooks")
. Once installed, you can use the chunk hook by loading the package and then calling the function chunk_head()
in your header.
Here is an example:
---
title: "Untitled"
output: pdf_document
---
```{r, include = FALSE}
library(knitrhooks)
chunk_head()
```
```{r, chunk_head = TRUE, echo = TRUE}
x <- sample(1)
```
Unfortunately, this will not display syntax highlighting, but as discussed within this issue, this is a limitation within how knitr processes the file.
Upvotes: 1
Reputation: 44867
If you don't put {r}
after the three backticks, rmarkdown will just pass the block on to markdown and it almost works. For example, this
```
```{r}
x = rnorm(1)
```
```
displays as
It's not quite right; the braces around the r
have been removed. (I think r-markdown did that, not markdown.) I don't know if there's an option to force them in, but they will appear if there's a non-letter ahead of the r
. You can put in a space, or (if you can figure out how) a zero width space, which R will display using "\u200B"
.
Upvotes: 1
Reputation: 4537
I found the bookdown book on Rmarkdown which has examples of R code chunks being rendered via Rmarkdown. The book source is available on GitHub and the relevant chapter is located here.
The chunk below works as desired. I can't explain why the `r ''` is required at the beginning of the block, but it is.
````markdown
`r ''````{r}
x = sample(1)
```
````
Upvotes: 4