Bookdown parameterised output formats

I am writing a document in R and I have to create tables. I use kableExtra package for pdf document. Now when I change output format to word document, there is a rendering error. I know that's because of using kableExtra package. Now i declare output format using parameterised reporting style in R and making tables also in such a way that if output format is pdf, render using kableExtra and if it is word, render using flextable. But there is an error in declaration of output format as a parameter. Can someone help me here? The index.Rmd YAML is attached below

You have to connect the parameter to the table somehow, and based on that have the table be evaluated based on the output format. Only declaring a parameter with the output format and then using this parameter to set the output format doesn't do much in this respect (in fact, it only adds an additional step).

What you can do instead is to define a helper function and utilise the asis engine for the relevant code chunks.

First, define two functions for PDF and Word, respectively:

```{r, include = FALSE}
is_word_output = function() {
  knitr::opts_knit$get("rmarkdown.pandoc.to") == "docx"
}

is_pdf_output = function() {
  knitr::opts_knit$get("rmarkdown.pandoc.to") == "latex"
}

These two functions will produce a TRUE or FALSE depending on the output. This can then be utilised via the eval chunk option.

For the PDF table, put the table-producing code in a chunk like this:

```{asis, eval = is_pdf_output()}
[TABLE CODE]
```

And, for the Word table:

```{asis, eval = is_word_output()}
[TABLE CODE]
```

The code chunks are only evaluated when eval = TRUE, which changes depending on the output format you've chosen.

@Equation solution would be the recommended one.

However, I would suggest to use the existing helpers, instead of retreiving directly some internal options.

  • knitr::is_latex_output() to check when rendering to pdf
  • knitr::pandoc_to("docx") to return TRUE when it rendering to word.

This is documented in this recipe for HTML and PDF