rquartogt

Automatic table numbering with gt package in R when rendering Quarto to Word doc


When rendering a Quarto document to Word and including several tables generated with gt(), something is applying an automatic "Table 1:" to the front of the tab_header(). It is always numbered as Table 1, regardless of the number of tables or if using the gt_group() function. This automatic numbering does not occur when rendering to html (there is no "Table 1:" appended in front of the header).

My main question: is there a way to have it number tables properly (e.g. Table 1, Table 2, etc.)?

Less important to me right now: is there a way to append a prefix or suffix to the numbering (e.g. Table A1, Table A2, etc.)?

---
title: "reprex"
format: docx
editor: visual
---


```{r}
library(gt)

mtcars |> 
  head() |> 
  gt() |> 
  tab_header(title = 'Testing title numbering')

mtcars |> 
  head() |> 
  gt() |> 
  tab_header(title = 'Testing title number 2')

gt_group(
  mtcars |> 
    head() |> 
    gt() |> 
    tab_header(title = 'Testing title number 3'),
  mtcars |> 
    head() |> 
    gt() |> 
    tab_header(title = 'Testing title number 4')
)
```

Solution

  • You could split each table in its own chunk and use tbl-caption instead of tab_header() in the chunk option to produce the table caption, i.e.

    ---
    title: "reprex"
    format: docx
    ---
    
    
    ```{r}
    #| label: tbl-example1
    #| tbl-cap: "Testing title numbering"
    
    library(gt)
    
    mtcars |> 
      head() |> 
      gt()
    ```
    
    
    ```{r}
    #| label: tbl-example2
    #| tbl-cap: "Testing title numbering 2"
    mtcars |> 
      head() |> 
      gt()
    ```
    

    enter image description here

    If you want to change the table table prefix you can change them globally in the crossreference e.g. change your yaml to

    ---
    title: "reprex"
    format: docx
    
    crossref:
      tbl-prefix: "Tab."
      tbl-title: "A."
    ---