Search code examples
rgt

How to data_color() a specific cell with gt() package in R


I would like to highlight specific elements of tables. The gt package produces great tables and data_color() brings some light in the whiteness.

library(gt)
head(mtcars) %>% 
  gt() %>% 
  data_color(
    columns = c("cyl"),
    colors = scales::col_numeric(
      palette = c("red", "orange"),
      domain = c(3, 10)
    ))

enter image description here

But how can I highlight a single cell, e.g. the first element of cyl? Sometimes I can manipulate the domain option for numeric values, but 6 appears multiple times. I tried this suggestion R gt package -background coloring a single cell, when it equals a certain value via tab_style() which does not work for me.

head(mtcars) %>% 
  gt() %>% 
  tab_style(
       style = cell_fill(color = 'grey'),
       locations = cells_body(
       columns = vars(cyl), 
       rows = cyl > 5
    ))

I'd like to adress a simple element instead of a domain.


Solution

  • You can index by position: rows = 1.

    head(mtcars) %>% 
      gt() %>% 
      tab_style(
        style = cell_fill(color = 'grey'),
        locations = cells_body(
          columns = c(cyl), 
          rows = 1
        ))
    

    enter image description here