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)
No matching items

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())

No matching items

Details

To make a reactive gt table:

  1. Install (install.packages("gt")) and load (library(gt)) the gt package.

  2. 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 the outputId argument of gt_output() to a unique value.

  3. Within the server function, call render_gt() and save its output as an element of the output list. Name the element after the outputId used above. For example, output$gt_table <- render_gt(). gt_output() will display the value of the output element whose name matches its outputId.

  4. 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 with gt().

  5. Optionally, use render_gt()’s other arguments (e.g., width, height, align) to control the appearance of the gt table.