2

In R Markdown, is there a way to change the echo option for different output types?

In the example below, I'd like to show my code on the html_document output (echo = TRUE), but would like to hide the code on the word_document output (echo = FALSE).

Currently, I have the global option to define knitr::opts_chunk$set(echo = TRUE) in my first code chunk, which seems to be required for the html_document code_folding option in the YAML header, but this also shows the code in the word_document output. If I remove this global option, I see the same outcome. Is there a way to define the echo option in the YAML header, under each of the output types (word_document vs. html_document)?

Thanks for your help with this.

---
title: "test2"
author: "Carina"
date: "February 13, 2020"
output:
  word_document: default
  html_document: 
    code_folding: show

---

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

2 Answers2

2

You can use the function is_html_output() to check whether you output is html or not and use that in your first chunk:

---
title: "test2"
author: "Carina"
date: "February 13, 2020"
output:
  word_document: default
  html_document: 
    code_folding: show

---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = knitr::is_html_output())
```
Uwe
  • 41,420
  • 11
  • 90
  • 134
Gilean0709
  • 1,098
  • 6
  • 17
1

Alternatively to Gilean0709's answer, we can use the string which is returned by the call to knitr::opts_knit$get("rmarkdown.pandoc.to"). This approach is taken from this answer.

---
title: "test2"
author: "Carina"
date: "February 13, 2020"
output:
  html_document:
    code_folding: show
  pdf_document: default
  word_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = knitr::opts_knit$get("rmarkdown.pandoc.to") == "html")
```
Uwe
  • 41,420
  • 11
  • 90
  • 134