I am using RMarkdown to produce pdf document. Is it possible to change font type in tables using kable_styling? If not, could you suggest any other package?
library(dplyr)
library(kableExtra)
kable(mtcars, align = "c", booktabs = TRUE) %>%
kable_styling(font_size = 12) %>%
row_spec(0, bold = T, color = "white", background = "gray")
This is somewhat tricky, because changing fonts in LaTeX is tricky. I don't have the Segoe UI font (that's a Windows font, right?), but here's something that works for me with a different font change in MacOS.
First, you need to use the xelatex
LaTeX engine. (You can probably do this using pdflatex
, but the commands would be different, and I don't know them.)
Second, you need to define a command to switch to the font you want. In the code below I called it \comicfont
and set it to switch to Comic Sans MS.
Third and fourth, you need to define environments to produce tables in this font. You need two environments, depending on whether you want the table inline (ctable
) or floating with a caption (capctable
).
Then when you want your table in the new font, you set table.envir
to the name of the appropriate environment. It gets set in kable_styling()
for inline tables and in kable
for floating tables. Here's an example that works for me:
---
title: 'Untitled'
output:
pdf_document:
latex_engine: xelatex
header-includes:
- \newfontfamily\comicfont[Path=/Library/Fonts/]{Comic Sans MS}
- \newenvironment{ctable}{\comicfont }{}
- \newenvironment{capctable}[1][t]{\begin{table}[#1]\centering\comicfont}{\end{table}}
---
```{r}
library(knitr)
library(kableExtra)
kable(head(mtcars), booktabs=TRUE, align = "c") %>%
kable_styling(table.envir="ctable", font_size=12) %>%
row_spec(0, bold = T, color = "white", background = "gray")
kable(head(mtcars), booktabs=TRUE, align = "c",
caption = "This table floats", table.envir = "capctable") %>%
kable_styling(font_size=12) %>%
row_spec(0, bold = T, color = "white", background = "gray")
```
This post https://tex.stackexchange.com/a/63975 gives an example on Windows which might be helpful.
Edited to add: the table.envir
parameter to kable_styling
is a pretty new addition; you should make sure you have the latest version of kableExtra
installed.