In R Markdown, I would like to be able to conditionally include certain chunks depending on what I am outputting to. For example if I am knitting a PDF I would like to include a small bit of LaTeX to do a page break, but if I am knitting HTML from the same document, I would like to skip that, or perhaps include something else. So how can a document "know" where it is going, and selectively include things?
1 Answer
I was able to get different inclusions and rendering with the following document:
---
output: html_document
---
```{r, results='asis', echo=FALSE}
library(knitr)
pandocto <- opts_knit$get("rmarkdown.pandoc.to")
if (pandocto == "docx") {
cat("## Word Heading\n\nHello world")
} else if (pandocto == "html") {
cat("## HTML Heading\n\nHello world-wide-web")
} else if (pandocto == "latex") {
cat("## LaTeX/PDF Heading\n\nHeLlO wOrLd")
}
```
```{r}
str(opts_knit$get()
```
If you vary the head YAML with what you need, perhaps one of:
output: html_document
output: pdf_document
output: word_document
you can see the difference. The tricks are knowing that rmarkdown
tells you the format to which pandoc
is rendering, and the use of results='asis'
in the block header to capture the output as raw-markdown (or latex, as appropriate).
I included the second block (str(...)
) so you can see what else is "known" during document compilation/rendering.