We can add a table header to the gt table with a title and even a
subtitle using the tab_header()
function. A table header is an optional
table part that is positioned just above the column labels table part. We
have the flexibility to use Markdown or HTML formatting for the header's
title and subtitle with the md()
and html()
helper functions.
Arguments
- data
The gt table data object
obj:<gt_tbl>
// requiredThis is the gt table object that is commonly created through use of the
gt()
function.- title
Header title
scalar<character>
// requiredText to be used in the table title. We can elect to use the
md()
andhtml()
helper functions to style the text as Markdown or to retain HTML elements in the text.- subtitle
Header subtitle
scalar<character>
// default:NULL
(optional
)Text to be used in the table subtitle. We can elect to use the
md()
andhtml()
helper functions to style the text as Markdown or to retain HTML elements in the text.- preheader
RTF preheader text
vector<character>
// default:NULL
(optional
)Optional preheader content that is rendered above the table for RTF output. Can be supplied as a vector of text.
Examples
Let's use a small portion of the gtcars
dataset to create a gt table.
A header part can be added to the table with the tab_header()
function.
We'll add a title and the optional subtitle as well. With the md()
helper
function, we can make sure the Markdown formatting is interpreted and
transformed.
gtcars |>
dplyr::select(mfr, model, msrp) |>
dplyr::slice(1:5) |>
gt() |>
tab_header(
title = md("Data listing from **gtcars**"),
subtitle = md("`gtcars` is an R dataset")
)
If the table is intended solely as an HTML table, you could introduce your
own HTML elements into the header. You can even use the htmltools package
to help arrange and generate the HTML. Here's an example of that, where two
<div>
elements are placed in a htmltools::tagList()
.
gtcars |>
dplyr::select(mfr, model, msrp) |>
dplyr::slice(1:5) |>
gt() |>
tab_header(
title =
htmltools::tagList(
htmltools::tags$div(
style = htmltools::css(
`text-align` = "center"
),
htmltools::HTML(
web_image("https://www.r-project.org/logo/Rlogo.png")
)
),
htmltools::tags$div(
"Data listing from ",
htmltools::tags$strong("gtcars")
)
)
)
If using HTML but doing something far simpler, we can use the html()
helper
function to declare that the text provided is HTML.
See also
Other part creation/modification functions:
tab_caption()
,
tab_footnote()
,
tab_info()
,
tab_options()
,
tab_row_group()
,
tab_source_note()
,
tab_spanner_delim()
,
tab_spanner()
,
tab_stub_indent()
,
tab_stubhead()
,
tab_style_body()
,
tab_style()