0

I realized that the layout of tables from knitr::kable() differs depending on the choice of making pdf or html. This can be 'solved' by choosing the most adopted choice for the argument format in knitr(). Many times I make html and pdf output of my .Rmd (different target audience - different habits) and there I have some difficulty for nice looking results for both of them with just a single .Rmd.

Ideally I want to work with just one Rmd file (for a given project ...) and adopt some details (eg the format="" argument in the function kable()) while running render() and avoid making 2 distinct versions of my Rmd (one for html and one for pdf).

My question is somehow related to R - kable() used in .Rmd does not show output in notebook. There it was suggested that using rmarkdown::metadata one can see what was written in the yaml header. In my yaml header I typically specify both the pdf and html. So finally this does not help me, since the result of rmarkdown::metadata will always be the same, independently of I call rmarkdown::render("test1.Rmd", output_format='pdf_document') or rmarkdown::render("test1.Rmd", output_format='html_document').

  1. Is there a way to know from within a chunk which output_format was chosen when calling rmarkdown::render() ?

  2. Another option might be the yaml-header : Can I specify in the header which 'format' argument should be chosen with knitr ? Something like

    title: "my title"  
    header-includes: \usepackage{float}
    output:
      html_document: 
        toc: true
        knitr_format: html
      pdf_document:
        number_sections: no
        knitr_format: latex
    

This way I'd like to have R run either knitr::kable(xx, format="latex") or knitr::kable(xx, format="html") depending how rmarkdown::render() was called...

As mentioned, I looked at rmarkdown::metadata, but this doesn't allow knowing how render() was called.

wraff
  • 9
  • 2

1 Answers1

0

One option would be to use knitr::is_html_output and/or knitr::is_latex_output to conditionally run your code depending on the output format:

---
title: "my title"  
header-includes: \usepackage{float}
output:
  pdf_document:
    number_sections: no
  html_document: 
    toc: true
---

```{r}
format <- if (knitr::is_html_output()) {
  "html"  
} else if (knitr::is_latex_output()) {
  "latex"
}

print(format)

knitr::kable(head(mtcars[1:4]), format = format)
```

enter image description here

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51