Conditionaly run a chunk - depends on an output format

I want to use rmarkdown and generate html as well as docx documents simultaneously. But depending on format (docx vs. html) a chunk should be run or not. Is it possible to find out what actually format is running? I use rmarkdown::render("demo.Rmd", output_format = "all") for the following Rmd file:

---
title: "Untitled"
author: "Robert"
date: "6 03 2020"
output:
  word_document: default
  html_document: default
---

# Ch 1


```{r cars}
library(knitr)
summary(cars)
```

```{r pressure}
# Pseudo code:
if (generate html)
kable(cars)

if (generate docx)
cars
```

You can do this with the function is_html_output() from the knitr package. There is also is_latex_output() if you want to allow for that option as well.

```{r}
library(knitr)

if(is_html_output()) {
  kable(cars)
} else {
  cars
}
```

If you want chunk evaluation to depend on document type, you could do:

```{r eval=is_html_output()}
kable(cars)
```
1 Like

I haven't tested it yet but it looks great. That's what I really need. Thank you.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.