Search code examples
rr-markdowngt

Numbered gt tables in rmarkdown


I'd like to number my tables made with the gt package in rmarkdown rendered pdf.
What I've tried
In a markdown doc, defining a function f that increments a variable every time it is called:

---
title: "."
output: bookdown::pdf_document2
---

```{r}
library(gt)
.i <- 1
f <- function() {.i <<- .i + 1 ; as.character(.i)}
```
```{r numbered_kable}
knitr::kable(head(mtcars,2), caption = "bla")|> kableExtra::kable_styling(latex_options = "HOLD_position")
```
```{r numbered_but_ugly}
mtcars |> head(2) |> 
  gt() |>
  tab_header(
    glue::glue("{f()} blabla2")
  )
```

Which works, but is a bit involved if both figures and tables need to be numbered. enter image description here
Question
What is the best way to number figures and tables in using the gt package?


Solution

  • There is a cross-referencing version that seems to be working

    devtools::install_github("rstudio/gt", ref="eff3be7384365a44459691e49b9b740420cd0851")
    

    -markdown code

    ---
    title: "."
    output: bookdown::pdf_document2
    ---
    
    ```{r}
    library(gt)
    library(dplyr)
    ```
    
    ```{r numbered_gt}
    mtcars %>% 
     head(2) %>% 
      gt() %>%
      tab_header(title="blabla2",
             label="tab:tab1")
    ```
    

    -output

    enter image description here