Change R Code based on Document Knitted

Hi,

I was wondering if anyone knew of a way to have the R code of a RMarkdown document changed by whether the document is being knitted to PDF vs HTML

Specifically, I have a document that I would like to knit to both, depending on the user. For the html_document, I would like to wrap many of my ggplots with plotly::ggplotly() to make them interactive. However, this does not work for the pdf_document, so I am fine just using the static version. Is there a way I can have the engine itself choose which version it outputs?

Currently, my workaround is to have a indicator at the top that I manually change about which it is (and then plots are wrapped in an ifelse(), but sometimes I forget to change it.

Thanks

1 Like

You can use knitr::opts_knit$get("rmarkdown.pandoc.to") to get a string indicating the output format. You can use your plotly code when it returns "html" and your alternate code for anything else. Set a boolean as

is_html <- knitr::opts_knit$get("rmarkdown.pandoc.to") == "html"

4 Likes