Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RMarkdown / Knitr: Hide code for Word document, but code folding in HTML document

For a project, I would like the knitr-output when choosing for a HTML to enable code folding, but to hide all code when knitting a word document.

My current RMarkdown YAML:

---
title: "Title"
author: "me"
output:
  bookdown::html_document2:
    code_folding: hide
    number_sections: false
  word_document:
    reference_docx: reference.docx
    # Option to hide code in word document?
  pdf_document:
    latex_engine: xelatex
bibliography: references.bib  
link-citations: yes
editor_options:
  markdown:
    wrap: 72
linestretch: 2
lang: en
---

Is there an option for the word_document YAML-tag to make this possible? Or another workaround or package? If you set echo=FALSE or include=FALSE in the R chuncks, then this also omits the code in the HTML document. Looked around in RMarkdown documentation and different forums, but can’t find a way to achieve this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option would be to use knitr::is_html_output to check whether you are rendering to HTML or not. This could then be used to conditionally set echo=FALSE for non-HTML output:

---
title: "Title"
author: "me"
output:
  word_document:
    # Option to hide code in word document?
    #reference_docx: reference.docx
  bookdown::html_document2:
    code_folding: hide
    number_sections: false
  pdf_document:
    latex_engine: xelatex
---

```{r include=FALSE}
if (!knitr::is_html_output()) knitr::opts_chunk$set(echo=FALSE)
```

```{r}
library(ggplot2)

ggplot(mtcars, aes(hp, mpg)) +
  geom_point()
```

Word Output

enter image description here

HTML Output

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading