Table (gt)
#| standalone: true
#| components: [viewer]
#| viewerHeight: 200
library(shiny)
library(bslib)
library(palmerpenguins)
library(gt)
library(dplyr)
penguins_summary <-
penguins |>
filter(!is.na(sex)) |>
group_by(island, species, sex) |>
summarize(
across(bill_length_mm:body_mass_g, \(x) median(x, na.rm = TRUE)),
.groups = "drop"
)
ui <- page_fluid(
gt_output("table")
)
server <- function(input, output) {
output$table <-
render_gt(
{
penguins_summary |>
group_by(island) |>
gt(rowname_col = "species") |>
tab_header(title = "Penguins in the Palmer Archipelago")
}
)
}
shinyApp(ui = ui, server = server)
library(shiny)
library(bslib)
library(palmerpenguins)
library(gt)
library(dplyr)
penguins_summary <-
penguins |>
filter(!is.na(sex)) |>
group_by(island, species, sex) |>
summarize(
across(bill_length_mm:body_mass_g, \(x) median(x, na.rm = TRUE)),
.groups = "drop"
)
ui <- page_fluid(
gt_output("table")
)
server <- function(input, output) {
output$table <-
render_gt(
{
penguins_summary |>
group_by(island) |>
gt(rowname_col = "species") |>
tab_header(title = "Penguins in the Palmer Archipelago")
}
)
}
shinyApp(ui = ui, server = server)
Relevant Functions
-
gt_output
gt_output(outputId)
-
render_gt
render_gt( expr, width = NULL, height = NULL, align = NULL, env = parent.frame(), quoted = FALSE, outputArgs = list())
Details
To make a reactive gt table:
Install (
install.packages("gt")
) and load (library(gt)
) the gt package.Call
gt_output()
in the UI of your app to create a div in which to display the table. Where you call this function within the UI functions will determine where the gt table will appear within the layout of the app. Set theoutputId
argument ofgt_output()
to a unique value.Within the server function, call
render_gt()
and save its output as an element of theoutput
list. Name the element after theoutputId
used above. For example,output$gt_table <- render_gt()
.gt_output()
will display the value of theoutput
element whose name matches itsoutputId
.Pass
render_gt()
a block of code, surrounded with{}
, that returns a gt table object. You can also return a data frame or tibble, which will be automatically converted to a gt table withgt()
.Optionally, use
render_gt()
’s other arguments (e.g.,width
,height
,align
) to control the appearance of the gt table.