Using gt in Markdown and creating a PDF

This seems like it should be so simple, but I have hit a wall.

I love gt, but I cannot get it to create a double-row column label when outputting to a PDF. Worked fine for HTML.

library(tidyverse)
library(gt)

knitr::opts_chunk$set(echo = TRUE)

df <- tribble(
  ~col1, ~col2, ~col3,
  1,  2,  3,
  4,  5,  6,
  7,  8,  9
)

df %>% 
  gt() %>% 
  tab_header(title="Testing how to do a line break"
             ) %>% 
  cols_label(
    col1=md("Single"),
    col2=md("Double  
            Entry"),  
    col3=md(html("And another<br>Double"))
  ) 

The HTML option yields the correct answer,
image

The PDF option, on the other hand...

image

It's always the little things that drive me crazy...

Not near a R terminal to test. But \newline is the latex equivalent of

Possibly need \newline

But that may not work depending how the table is actually encoded in latex. \par might also be worth a look?

Nope. That didn't work.

It looks like my second line stripped a slash. It should have been. \ \newline but with no spaces

But there is a function in kableExtra called line break that is designed to do this. GtSummary can output to kable

Alternatively I believe flextable (also an output option for GT) can handle \n at least in newer versions.

Just realised you are using gt rather than GT summary and there is no conversion function from gt.

df %>%
    flextable() %>%
    flextable::set_caption("Testing how to do a line break") %>%
    set_header_labels(col1="Single", col2="Double\nEntry", col3="Another\nDouble Entry")

Would do what you want IF you aren't constrained to GT as a function

Kable seems to be a pain to do it in the headers. Hux may work - but I'm getting basic errors with hux.

seems to be related to your way of creating a new line.

I think I have seen a function to create new lines that would work in html and latex outputs, but I could not find it anymore (sorry...) anyone knows better ?

It's not optimal, but you could use gtsave() to save the image as a png, and insert it that way for pdf/latex. If you want multiple output formats, you can have separate table output by determining the output format - i.e gt table for html etc, and image of gt for pdf/latex, using is_latex_output().
example

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.