0

I have a function that produces a table. I would like people to be able to use this code to inside of RMarkdown/Quarto documents. I would also like to prettify this table, which would be aided by knowing whether the table is heading for HTML, PDF, or Word.

Is there a way to use code to detect what kind of document is about to be built?

I know it's possible to use code to detect whether or not one is in knitr, as per this question.

I am also aware of knitr::opts_knit$get("out.format"), but this just returns "markdown" for HTML, PDF, and Word output alike, at least for standard RMarkdown or Quarto usage.

NickCHK
  • 1,093
  • 7
  • 17
  • 1
    check out the [`knitr::is_latex_output`](https://www.rdocumentation.org/packages/knitr/versions/1.19/topics/is_latex_output) and also `knitr::is_html_output()` – shafee Feb 26 '23 at 09:37
  • Oh man my Google skills have clearly gone down the drain for me to have not found these over the past hour. This totally works ,thank you so much! If you post as an answer I will accept. – NickCHK Feb 26 '23 at 09:44
  • On further inspection I have actually used knitr::is_latex_output previously, but had forgotten all about it. Even more devastating. – NickCHK Feb 26 '23 at 09:47
  • Ah, it's alright. This happens sometime : ) – shafee Feb 26 '23 at 13:14

2 Answers2

1

Try with knitr::is_latex_output and knitr::is_html_output().

test.qmd

---
title: "Output Format"
format: pdf
---

```{r}
library(knitr)

if(is_latex_output()) {
  
  print("Output format is pdf")
  # and other codes intended for pdf output

} else if(is_html_output()) {
  
  print("Output format is html")
  # and other codes intended for html output
  
} else {
  
  print("Output format is docx")
  # and other codes intended for word output
}
```

If you need more granularity, knitr::pandoc_to() tells you exactly the Pandoc output format, e.g., html, latex, docx, and so on.


You may also want to check out the Conditional Content from Quarto Docs.

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
shafee
  • 15,566
  • 3
  • 19
  • 47
0

In the header, between the "---" there's something called "output:", there is where you can know it!

Lucas
  • 302
  • 8
  • I mean how can I use code to detect it, given that my function will be used by many people who are not me. I will clarify. – NickCHK Feb 26 '23 at 09:36