Skip to content

Instantly share code, notes, and snippets.

@jmcastagnetto
Last active May 30, 2019 14:33
Show Gist options
  • Save jmcastagnetto/ea6ba66896bf8ba88627ff149bab68d7 to your computer and use it in GitHub Desktop.
Save jmcastagnetto/ea6ba66896bf8ba88627ff149bab68d7 to your computer and use it in GitHub Desktop.
Example of conditional chunk evaluation depending on document output type
---
title: "Example of conditional chunk evaluation"
author: "Jesús M. Castagnetto"
date: "2019-05-30"
output:
pdf_document:
toc: true
number_sections: true
html_document:
df_print: paged
mathjax: null
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
warning = FALSE,
message = FALSE)
```
# How to evaluate chunks depending on the document output
To get conditional chunk evaluation we make use of the functions `knitr::is_html_output()` and `knitr::is_latex_output()`.
We´ll create a simple plot:
```{r}
plot_iris <- ggplot2::ggplot(iris, ggplot2::aes(x = Sepal.Length, y = Sepal.Width)) +
ggplot2::geom_point(ggplot2::aes(color = Species))
```
## The following chunk will be evaluated only if the output is HTML
And the code will generate an interactive plot using the `plotly` package.
```{r eval=(knitr::is_html_output())}
plotly::ggplotly(plot_iris)
```
## And the following, only if the output will be PDF
The code here will generate a regular plot
```{r eval=(knitr::is_latex_output())}
plot_iris +
ggplot2::theme_minimal()
```
## And this one will appear in both
Just a simple table
```{r}
knitr::kable(head(iris, 5), booktabs = TRUE)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment