How can I change the color or highlight a word in a gt table using str_detect (or regex)?

72 Views Asked by At

This is what I've got, but I get Error: object 'Name' not found when I run the code. Any ideas on how to proceed?

library(gt)

data <- data.frame(
  Name = c("John Doe", "Jane Smith", "Bob Johnson"),
  Age = c(30, 25, 35))

highlight_word <- "Doe"


 gt(data) |> 
  tab_style(
    locations = cells_body(columns = Name),
    style = list(cell_text(color = 
                    ifelse(str_detect(Name, highlight_word), "yellow", "white")))) 
 

1

There are 1 best solutions below

1
On BEST ANSWER

A couple of approaches to try. One uses fmt_markdown to use Markdown-formatted text in your gt table with rendering. The other uses text_transform to modify formatted strings in targeted cells in the table. The latter requires a function to transform the text as desired.

library(gt)
library(stringr)
library(tidyverse)

With fmt_markdown:

data |>
  mutate(Name = str_replace(Name, highlight_word, paste0('<a style = "color:yellow">', highlight_word, '</a>'))) |>
  gt() |>
  fmt_markdown(columns = Name)

With text_transform:

gt(data) |>
  text_transform(locations = cells_body(columns = Name),
                 fn = \(x) {
                   str_replace(x, highlight_word, paste0('<a style = "color:yellow">', highlight_word, '</a>'))
                 })

Output

gt table with yellow word in cell