rr-markdownknitrbookdown

Include code chunks in R bookdown conditioned on the selected output format


I would like to be able to render my R book in both tex and html so that I get two versions of the same book. Is it possible to execute certain code chunks only if the appropriate output format has been selected for rendering?

I have created an example with only an index.Rmd, which hopefully shows what I am trying to achieve.

--- 
title: "Untitled"
site: bookdown::bookdown_site
output: bookdown::gitbook
documentclass: report
always_allow_html: true
---

```{r packages, include=FALSE}
library(datasets)
library(dplyr)
library(kableExtra)
```

Lorem ipsum

```{r html_table, echo=FALSE, warning=FALSE}
kbl(cbind(mtcars, mtcars), format = "html") %>%
  kable_paper() %>%
  scroll_box(width = "500px", height = "200px")
```

```{r latex_table, echo=FALSE, warning=FALSE}
kbl(mtcars, format = "latex")
```

html_table should only be included when running bookdown::render_book('index.Rmd', 'bookdown::gitbook') and latex_table should only be included when running bookdown::render_book('index.Rmd', 'bookdown::pdf_book'), so there should never be both of them in an output document.

I tried including the code chunks conditioned on knitr::opts_knit$get()$out.format, but even when rendering to a pdf_book, the value of this object is still "markdown".

```{r format, echo=FALSE, warning=FALSE}
ifelse(knitr::opts_knit$get()$out.format == "markdown",
       is_html <- TRUE,
       is_html <- FALSE)
```

```{r html_table, include=is_html, echo=FALSE, warning=FALSE}

[...]

```{r latex_table, include=!is_html, echo=FALSE, warning=FALSE}

[...]

Solution

  • You can use the function knitr::pandoc_to() for this:

    ---
    title: "Conditional Chunks: Output Format"
    output: pdf_document
    #output: html_document
    date: "2023-09-27"
    ---
    
    ```{r, eval = knitr::pandoc_to('html')}
    plot(mtcars)
    ```
    
    ```{r, eval = knitr::pandoc_to('latex')}
    plot(mtcars)
    ```