rpdflatexquartogt

Creating a pdf using Quarto, can't put a line break in a column table


Here is a sample of my code, where I want to break up the column "Sepal.Length" on two lines.

---
title: "Unbreakable Line"
format: pdf
editor: visual
---

{r}
#| label: load-packages
#| include: false

library(tidyverse)
library(magrittr)
library(tinytex)
library(gt)


{r}

iris %>% 
  head(10) %>% 
  gt() %>% 
    cols_label(
      Sepal.Length = md("Sepal<br>Length")
    )


It works fine when I preview the chunk, but when I render, I get this error:

"Warning: HTML tags found, and they will be removed.* Set options(gt.html_tag_check = FALSE) to disable this check."

I've tried taking out the md() and using "\n", but that just gives me a space. Any hints on how to get a line break here?


Solution

  • First, as you are rendering to pdf HTML tags will not work and get dropped as the warning is telling you. Instead, you have to use LaTex to add a linebreak, e.g. you can use \\\\. However, this will not work either as under the hood the backslashes get escaped and replaced with \\textbackslash{} in the resulting LaTeX code.

    To prevent the escaping, functions from other packages like knits::kable or gtsummary::as_kable_extra offer an escape= parameter which can be set to FALSE. This is however not the case for gt::as_latex.

    One possible workaround to fix that would be to use a custom knit_print method to overwrite the knit_print method provided by gt. Doing so allows to replace the \\textbackslash{} added by gt::as_latex with the desired \\. Basically the same is done under the hood by e.g. gtsummary::as_kable_extra.

    Note: You have to define or add the custom knit_print method after loading gt, otherwise it gets overridden by the gt default.

    ---
    title: "Unbreakable Line"
    format: pdf
    editor: visual
    ---
    
    ```{r}
    #| label: load-packages
    #| include: false
    
    library(tidyverse)
    library(tinytex)
    library(gt)
    ```
    
    ```{r echo=FALSE}
    knit_print.gt_tbl <- function(x, ...) {
      if (knitr::is_latex_output()) {
        res <- gt::as_latex(x)
        res[[1]] <- gsub(
          "\\textbackslash{}",
          "\\",
          res[[1]],
          fixed = TRUE
        )
    
        return(res)
      }
    
      gt:::knit_print.gt_tbl(x)
    }
    
    registerS3method(
      "knit_print", "gt_tbl", knit_print.gt_tbl,
      envir = asNamespace("knitr")
    )
    ```
    
    ```{r echo=FALSE}
    iris %>%
      head(10) %>%
      gt() %>%
      cols_label(
        Sepal.Length = "Sepal\\\\Length"
      )
    ```
    

    enter image description here