6  Output and citing results in the text

6.1 gtsummary tables are used by “converting” them

When displayed or saved, gtsummary tables are converted into the format of another table package.

Function Converts to Main use
as_gt() gt HTML, PNG, PDF, RTF
as_flex_table() flextable Word, PowerPoint
as_kable() knitr::kable Markdown
as_kable_extra() kableExtra LaTeX / PDF
as_tibble() tibble Processing as data, Excel export

6.2 Converting to gt and refining further

Decorations that gtsummary does not offer can be added with gt functions after converting to gt.

Warning

After converting with as_gt() or similar, you can no longer use gtsummary’s modify_*() or add_*(). Finish all processing in gtsummary first, and convert at the very end.

6.3 Extracting as data: as_tibble()

If you want to keep the raw column names, use as_tibble(col_labels = FALSE). You can also write it out to Excel with writexl::write_xlsx() or similar.

6.4 Saving to a file (on your own PC)

Files cannot be saved from the browser, so run this part in your own R environment.

6.4.1 Word (.docx)

Journals often ask for tables in Word for manuscript submission. Save via flextable.

library(flextable)

tbl |>
  as_flex_table() |>
  save_as_docx(path = "table1.docx")

To combine several tables into one Word file:

save_as_docx(
  "Table 1" = as_flex_table(tbl1),
  "Table 2" = as_flex_table(tbl2),
  path = "tables.docx"
)

6.4.2 HTML / PNG / PDF

tbl |> as_gt() |> gt::gtsave("table1.html")
tbl |> as_gt() |> gt::gtsave("table1.png")   # requires the webshot2 package
tbl |> as_gt() |> gt::gtsave("table1.pdf")

6.4.3 Writing the whole manuscript in Quarto / R Markdown

If you write the table code in a code chunk in Quarto (.qmd) or R Markdown, it is automatically converted into the appropriate format for format: docx / html / pdf. For Word output it automatically becomes a flextable, so you do not need to think about the conversion.

---
title: "Results"
format: docx
---

```{r}
library(gtsummary)
trial |> tbl_summary(by = trt) |> add_p()
```

6.5 Citing numbers in the text: inline_text()

When writing something like “the median age in the Drug A group was 46 years (Q1, Q3: 37, 60)” in the text, copying numbers from the table by hand invites transcription errors. With inline_text() you can extract exactly the same numbers as in the table.

For regression tables, you can extract the estimate and confidence interval together.

TipUsing it in Quarto / R Markdown

If you write `r inline_text(t_reg, variable = trt, level = "Drug B")` in the text, the number is embedded at render time. When you update the data, the numbers in the text follow automatically.

ImportantChapter summary
  • Finish processing, then convert at the end: as_gt() (HTML/images), as_flex_table() (Word), as_tibble() (data)
  • Word: as_flex_table() |> flextable::save_as_docx()
  • Pull numbers for the text from the table with inline_text() → prevents transcription errors