4

Showing the code in PDF can be long and distracting to some readers or clients, but I would leave it as an option in the HTML version if they want to reproduce it or verify what I've done. Depending on whom I work with, I may share one or the other (or both), but I want to avoid changing the Rmd script each time to produce them.

Thus, I want to be able to knit my R Markdown script to HTML and PDF in a way so that the HTML output can show the code (with code_folding in the output: html_document options), but prevent the code from appearing in my PDF output.

Is there a way to do that without recoding part of the script each time?

Take this example R Markdown text:

---
title: "Title"
output: 
  pdf_document:
    df_print: kable
  html_document:
    code_folding: show
    df_print: paged
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

```{r mtcars}
# I want to make this code visible when I knit to HTML, but hidden when I knit to PDF. 
# How do I do that?
mtcars[1:2, 1:4]
```

It will show the mtcars chunk when it's knitted.

I can change knitr::opts_chunk$set(echo = TRUE) to knitr::opts_chunk$set(echo = FALSE) in the setup chunk to prevent the code from showing in the PDF output, but the code will disappear in the HTML output as well.

code_folding: hide can hide the code for html_document output options and allows the reader to see the code if necessary. However, code_folding: hide does not work for pdf_document output options. Is there an alternative that I can use?

LC-datascientist
  • 1,960
  • 1
  • 18
  • 32

1 Answers1

4

Maybe use is_html_output in eval and echo

---
title: "Title"
output: 
 html_document:
   code_folding: show
   df_print: paged
  pdf_document:
    df_print: kable
 ---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

```{r mtcars, eval = knitr::is_html_output(), echo = knitr::is_html_output()}
# I want to make this code visible when I knit to HTML, but hidden when    I knit to PDF. 
 # How do I do that?
 mtcars[1:2, 1:4]
 ```

-output html

enter image description here

-output pdf

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    Wonderful! I didn't know about that function. By extension, instead of applying to every chunk, I can apply it to the code in the `setup` chunk to change the default behaviour: `knitr::opts_chunk$set(echo = knitr::is_html_output())`. – LC-datascientist Jul 28 '21 at 00:58