[SOLVED] R gt package -background coloring a single cell, when it equals a certain value

Issue

This Content is from Stack Overflow. Question asked by Marco

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

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

Since you do not provide the value of pal in your code, I have omitted it here. But the example shows coloring at the cell level, with a condition that the value of column c is greater than 3.

library(gt)
tab_1 <-
    dplyr::tibble(a = 1:8, b = 1:8, c = 1:8) %>%
    gt() %>%
    data_color(
        columns = vars(a),
        colors = scales::col_numeric(
            palette = c('red'),
            domain = c(1, 8)
        )
    ) %>%
    data_color(
        columns = vars(b),
        colors = scales::col_numeric(
            palette = 'green',
            domain = c(1, 8)
        )
    ) %>%
    tab_style(
        style = cell_fill(color = 'grey'),
        locations = cells_body(
        columns = vars(c), 
        rows = c > 3
    ))

tab_1

This Question was asked in StackOverflow by strikerman and Answered by Susan Switzer It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?

Exit mobile version