The problem

I want to embed an RMarkdown chunk verbatim into an RMarkdown document, to use for teaching how to write RMarkdown. I’ve tried the whole bag of tricks here (http://rmarkdown.rstudio.com/articles.html), but none work. The zero width space trick works for HTML, but fails to compile to PDF using pandoc.

The solution

It’s terribly ugly, but works. First, define a function to cat something, preceeded by a four-space indent, followed by a newline.

catn <- function(x="") cat("    ", x, "\n")

Then catn out the Rmarkdown that you’d like to actually show up in your Rmarkdown document. Your code chunk would look like this, with echo=FALSE and results='asis' so that the RMarkdown is printed verbatim into the output.

```{r, echo=FALSE, results='asis'}
catn("# Introduction")
catn()
catn("This is my first RMarkdown document!")
catn()
catn("## Let's embed some R code")
catn()
catn("```{r}")
catn("head(mtcars)")
catn("```")
catn()
catn("That's the end of the code chunk, now we're back in regular markdown.")
```

Here’s what you’d get in your output:

 # Introduction 
  
 This is my first RMarkdown document! 
  
 ## Let's embed some R code 
  
 ```{r} 
 head(mtcars) 
 ``` 
  
 That's the end of the code chunk, now we're back in regular markdown. 

Now we’re back in our “top level” markdown document used for teaching!