Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Created October 31, 2023 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewheiss/36da0529a5dd4f7a8241fd886b34f5db to your computer and use it in GitHub Desktop.
Save andrewheiss/36da0529a5dd4f7a8241fd886b34f5db to your computer and use it in GitHub Desktop.
---
title: Table testing
format:
html: default
pdf: default
---
```{r, warning=FALSE, message=FALSE}
library(tidyverse)
library(gt)
example_table <- tibble::tribble(
~thing1, ~thing2, ~thing3,
1, 2, "3",
4, 5, "6",
7, 8, "Really long text goes here blah blah blah it just keeps going forever, maybe even off the side of the page? Can we get it to trail off? Maybe?!"
)
```
This works fine in HTML but breaks in PDF:
```{r eval=TRUE}
example_table %>%
gt() %>%
cols_label(
thing1 = "Thing", thing2 = "Other thing", thing3 = "One more longer thing"
) %>%
cols_width(
thing1 ~ pct(10),
thing2 ~ pct(15),
thing3 ~ pct(75)
)
```
It breaks in PDF because `gt()` emits things like `10%`, which isn't valid LaTeX:
```tex
\begin{longtable*}{>{\raggedleft\arraybackslash}p{10%}>{\raggedleft
\arraybackslash}p{15%}>{\raggedright\arraybackslash}p{75%}}
```
We can feed widths like `3in` or `6cm` though:
```{r}
example_table %>%
gt() %>%
cols_label(
thing1 = "Thing", thing2 = "Other thing", thing3 = "One more longer thing"
) %>%
cols_width(
thing1 ~ "1in",
thing2 ~ "1.25in",
thing3 ~ "3.5in"
)
```
And it works for HTML too, but then you have to think about inches in HTML, and that's weird. Percents are better there. Also, here I arbitrarily chose 1, 1.25, and 3 inches, but those aren't the original 10%, 15%, 75% proportions that I used at the beginning. If I have 6 inches of page width to work with, I'd need 75% of that for the 75% column, or 6 × 0.75 = 4.5 inches.
Doing that math is tedious though. And using inches in HTML is annoying.
So we can make a little wrapper function that uses percents when rendering to HTML and that converts percents to inches when rendering to PDF:
```{r}
my_pct <- function(x, page_width = 6) {
if (knitr::pandoc_to("latex")) {
paste0(page_width * (x / 100), "in")
} else {
gt::pct(x)
}
}
example_table %>%
gt() %>%
cols_label(
thing1 = "Thing", thing2 = "Other thing", thing3 = "One more longer thing"
) %>%
cols_width(
thing1 ~ my_pct(10),
thing2 ~ my_pct(15),
thing3 ~ my_pct(75)
)
```
(It's a little wider than the text block width, but I think that's because of internal cell padding)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment