Capturing 'output_format' from rmarkdown :: render as a variable

I am using RStudio with knitr etc. to create reproducible reports and want to have better versions for Word and PDF documents. I prefer working with LaTeX, but end users prefer the flexibility of editable Word documents.

I wrote an ifelse statement, which essentially says: "if it is render ed as a word document, create a kable table in the markdown method, otherwise create a kable table in LaTeX, and then perform manipulations to make the table look better (shaded lines, etc. .).

I don’t understand how the rmarkdown::render ing process works to capture output_format , but is there a way to save this as a variable and use it in the ifelse statement?

A minimal example is to save this code as test.Rmd :

 format <- output_format #(somehow captured as a variable) printTable <- function(data = df, format = format){ if (format %in% 'pdf_document') { # create nice latex table } else { # create markdown table } } 

Then when running this code:

 rmarkdown::render(input = "test.Rmd", output_format = c("word_document", "pdf_document")) 

in different versions of the report the correct tables will be indicated.

+5
source share
1 answer

You can access the output format via knitr::opts_knit$get("rmarkdown.pandoc.to") . This will return a string with the target output format. Here is an example:

 --- title: "Untitled" output: html_document --- ```{r} library(knitr) opts_knit$get("rmarkdown.pandoc.to") ``` 

This returns "html" for html_document, "docx" for word_document, and "latex" for pdf_document.

+7
source

All Articles