9.1 LaTeX or HTML output

LaTeX and HTML are two commonly used output formats. The function knitr::is_latex_output() tells you if the output format is LaTeX (including Pandoc output formats latex and beamer). Similarly, the function knitr::is_html_output tells you if the output format is HTML. By default, these Pandoc output formats are considered HTML formats: markdown, epub, html, html4, html5, revealjs, s5, slideous, and slidy. If you do not think a certain Pandoc format is HTML, you may use the excludes argument to exclude it, e.g.,

# do not treat markdown as an HTML format
knitr::is_html_output(excludes = "markdown")
## [1] TRUE

If a certain output element can only be generated in LaTeX or HTML, you can use these functions to conditionally generate it. For example, when a table is too big on a PDF page, you may include the table in an environment of a smaller font size, but such a LaTeX environment certainly will not work for HTML output, so it should not be included in HTML output (if you want to tweak the font size for HTML output, you may use CSS). Below is a full example:

---
title: Render a table in a tiny environment
output:
  pdf_document: default
  html_document: default
---

```{r, setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
options(knitr.table.format = function() {
  if (knitr::is_latex_output()) 'latex' else 'pandoc'
})
```

The LaTeX environment `tiny` is only generated for LaTeX output.

```{r, include=knitr::is_latex_output()}
knitr::asis_output('\n\n\\begin{tiny}')
```

```{r}
knitr::kable(mtcars)
```

```{r, include=knitr::is_latex_output()}
knitr::asis_output('\\end{tiny}\n\n')
```

By comparison, below is the table with the normal font size.

```{r}
knitr::kable(mtcars)
```

The key in the above example is the chunk option include = knitr::is_latex_output(). That is, the environment \begin{tiny} \end{tiny} is only included when the output format is LaTeX. The two tables in the example will look identical when the output format is not LaTeX.

In Section 5.1, we used these functions to change the text color for HTML and LaTeX output. In Section 4.14, we showed an animation example, which also used this trick. The code chunk that generated the animation for HTML output and static images for LaTeX output is like this:

```{r animation.hook=if (knitr::is_html_output()) 'gifski'}
for (i in 1:2) {
  pie(c(i %% 2, 6), col = c('red', 'yellow'), labels = NA)
}
```

These conditional functions can be used anywhere. You can use them in other chunk options (e.g., eval for conditional evaluation of the chunk), or in your R code, e.g.,

```{r, eval=knitr::is_html_output(), echo=FALSE}
cat('You will only see me in HTML output.')
```

```{r}
if (knitr::is_latex_output()) {
  knitr::asis_output('\n\n\\begin{tiny}')
}
```