rpdfr-markdownknitrgtsummary

gt_summary table not being correctly displayed after knitted to PDF format in R-Markdown (wrong order)


I am trying to write a report using R-Markdown and tables made with gt_summary but when i export to pdf format, something goes wrong and the table shows up before even the title. I knitted do html and doc format without any issues.

Here is how the pdf was knitted:

enter image description here

I reproduced the error with the mtcars dataset in the code below:

---
title: "Mtcar example"
author: "Pedro Rizzi"
date: "2024-12-23"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r packages loading}
library(tidyverse)
library(gtsummary)
```

## Example

Here is some text before the table.

```{r table}

mtcars |> select(mpg, disp, hp) |>  tbl_summary()
```

Here is some text after the table.

Solution

  • For some reason, tbl_summary() is defaulting to positioning the table using the LaTeX code !t, which means "force the table to the top of the page". You hardly ever want that.

    To fix it, you need the gt package functions as_gt() and tab_options(). Modify your table creation by adding these at the end, e.g.

    mtcars |> select(mpg, disp, hp) |>  tbl_summary() |>
        as_gt() |>
        tab_options(latex.tbl.pos = "h")
    

    This uses table position h, which means "put the table here". Another possible choice would be t, which means "put the table at the top of the page if it makes sense", or an empty string which says "use the LaTeX defaults".