Search code examples
fontsr-markdownkablekableextra

RMarkdown - different font types in table using kable or huxtable, output to pdf?


Using huxtable, output to html with different fonts for different cells/rows is a breeze. Not so much with pdf. This is not really a new question, but a specific version of RMarkdown - different font types in table using kable? and Change font of Kable in Rmarkdown pdf

I have used the answer given from https://stackoverflow.com/a/54735453/4927395 to create the output in the image below from rmarkdown (on my windows pc). Note that the 'environment' code will change the font for the table (the whole table), but that text after the chunk is in the font specified for the table. Suggestions to fix that? Also, I could not get the floating example to work on my computer, which is why it is commented out. I like huxtable, but haven't seen examples of the font selected for the table (where it is different to the main font) working on the web. Open to exploring other table packages if absolutely necessary.

    ---
title: "Reprex selecting font for kable table output to pdf"
output: 
  pdf_document:
    latex_engine: xelatex
header-includes:
  \usepackage{fontspec}
  \setmainfont[Path=C:/windows/fonts/]{SHOWG.TTF}
  \newfontfamily\arialfont[Path=c:/windows/fonts/]{ARIAL}
  \newenvironment{ctable}{\arialfont }{}
  \newenvironment{capctable}[1][t]{\begin{table}[#1]\centering\arialfont}{\end{table}}
---

here is some text

```{r}
library(knitr)
library(kableExtra)
#This works, though leaves the selected font active for text after the chunk
kable(head(mtcars), booktabs=TRUE, align = "c") %>% 
   kable_styling(table.envir="ctable", font_size=12) %>%
   row_spec(0, bold = T, color = "white", background = "gray")
#This next bit doesn't work
#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")
```


here is some more text

output


Solution

  • Indeed, here is how to do this in huxtable (I'm the package owner). You'll need xelatex installed, and the LaTeX "fontspec" package. You’ll also need huxtable version 4.4.0 or above, currently available on github:

    install_github("hughjonesd/huxtable")
    

    In your rmarkdown header:

    output:
       pdf_document:
         latex_engine: xelatex
    
    

    In an R code chunk:

    library(dplyr)
    library(huxtable)
    options(huxtable.latex_use_fontspec = TRUE)
    
    mtcars %>%
          head() %>%
          as_huxtable() %>% 
          set_font("Times New Roman")