knitr::is_latex_output()
and knitr::is_html_output()
allow checking if the current output type LaTex or HTML respectively.
Is there an equivalent for Word as an output format?
If not, what would be the most simple to use workaround?
---
title: "MWE for different file formats in namespace:knitr"
output:
pdf_document: default
html_document: default
word_document: default
---
```{r}
if (knitr::is_html_output()) {
cat("HTML")
}
if (knitr::is_latex_output()) {
cat("LATEX")
}
if (knitr::is_word_output()) {
cat("WORD")
}
## Error: 'is_word_output' is not an exported object from 'namespace:knitr'
```
As of knitr 1.31 (released in January 2021), you can use knitr::pandoc_to()
in either of the following ways:
```{r}
if (knitr::pandoc_to("docx")) {
cat("Word")
}
```
```{r, include=knitr::pandoc_to("docx")}
cat("Word")
```
To conditionally output literal text content (rather than R code), it's easiest to use an asis
chunk (note that we need to use the echo
option instead of include
):
```{asis, echo=knitr::pandoc_to("docx")}
This will only appear in Word documents.
```
```{asis, echo=knitr::pandoc_to("docx", "pdf")}
This will be appear in Word and PDF documents.
```
In earlier versions of knitr, you can use an internal knitr function to get the type you want:
is_word_output <- function(fmt = knitr:::pandoc_to()) {
length(fmt) == 1 && fmt == "docx"
}