Search code examples
rtidyversegt

Conditionally overwrite cell text with gt::gt()


With {gt}, you can conditionally style cells based on the values in another column in your dataframe. Is there a way to conditionally overwrite the cell display values based on a different column? In the reprex below, I'd ideally like to display a ✓ when override == "x". This will end up being a filterable/sortable table, so I'd need to change the displayed values without changing the underlying data from numeric.

gt::fmt() takes in custom functions as arguments, but it looks like the custom function can only reference the column itself, not another column.

library(tibble)
library(gt)

data <- 
  tribble(
    ~display, ~override,
    0.8, NA_character_,
    0.3, NA_character_,
    1, "x",
    1, NA_character_,
    0, "y",
    0, NA_character_
  )

data %>%
  gt() %>%
  data_color(display, palette = "PuBu") %>%
  fmt_percent(display, decimals = 0) %>%
  tab_style(style = list(cell_fill("green4")),
            locations = cells_body(columns = display,
                                   rows = override == "x")) %>%
  tab_style(style = list(cell_fill("red3")),
            locations = cells_body(columns = display,
                                   rows = override == "y"))

enter image description here

Created on 2025-02-21 with reprex v2.1.1


Solution

  • You could use text_transform with a custom function that inserts for the x-val-rows in display. Source: this

    library(tibble);library(gt)
    
    data <- 
      tribble(~display, ~override,0.8, NA_character_, 0.3, NA_character_, 1, "x", 1, NA_character_, 0, "y", 0, NA_character_) %>%
      gt() %>%
      data_color(display, palette = "PuBu") %>%
      fmt_percent(display, decimals = 0) %>%
      text_transform(\(x) "✓", cells_body(columns = display, rows = override == "x")) %>%
      tab_style(list(cell_fill("green4")), cells_body(display, override == "x")) %>%
      tab_style(list(cell_fill("red3")), cells_body(display, override == "y"))