We want kable to generate html for the table when the document output format is html and latex for the table when the document output format is PDF. We can determine the output format from within the rmarkdown document using the knitr functions is_html_output() and is_latex_output(). Below is a complete rmarkdown document using the example you provided. I've added a test for the output document type in the code chunk where the table is generated. Then, within the kable function, we use the format argument to set the table output to "html" or "latex", depending on the type of document we're generating.
When I tried to render the document to PDF, I got a latex error: ! LaTeX Error: Unknown float option 'H'.. I've seen this before and thought it had been fixed in more recent versions of kableExtra, so I'm not sure why it's happening here. In any case, if you get the same error, it can be addressed by explicitly loading a bunch of latex packages by adding the following code to the YAML:
header-includes:
- \usepackage{booktabs}
- \usepackage{longtable}
- \usepackage{array}
- \usepackage{multirow}
- \usepackage[table]{xcolor}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage[normalem]{ulem}
Here's the full rmarkdown document.
---
title: "Testing Document"
author: Lukas
date: "`r Sys.time()`"
output:
pdf_document:
latex_engine: pdflatex
html_document:
toc: true
toc_float: true
code_folding: show
fontfamily: palatino
editor_options:
chunk_output_type: console
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE,
message = FALSE, fig.align = "center",
fig.height = 2.5, fig.width = 8)
library(tibble)
library(knitr)
library(dplyr)
library(kableExtra)
```
# a small table
```{r}
a5 <- tibble(
x = c(-1, 1, 2),
f = c(0.2, 0.1, 0.7),
Fx = cumsum(f)
)
# Get output document type and use as the format argument in kable function
table_format = if(is_html_output()) {
"html"
} else if(is_latex_output()) {
"latex"
}
a5 %>%
setNames(c("x", "f(x)", "F(x)")) %>%
t() %>%
kable(format = table_format, booktabs=TRUE) %>%
kable_styling(latex_options = c("striped"))
```