Search code examples
rgtgtextras

Set background colors for the cells of multiple columns based on string contents using gt package


Given a small dataset as follows:

library(gt)
library(tidyverse)

id <- c(1,2,3,4,5)
res1 <- c("true", "true", "false", "true", "false")
res2 <- c("false", NA, NA, "true", "true")
df <- data.frame(id, res1, res2)

df %>% 
  gt()

Out:

enter image description here

For columns res1 and res2, let's say if value content are trues, I'll need to highlight that cell with red background color, if falses, highlight with green color, for other cases, keep their colors as original.

How could I achieve that using gt package in R?

Note: the example code and outcome from the link below are for values, not strings as this case.

enter image description here

References:

https://gt.rstudio.com/reference/data_color.html


Solution

  • Using as per manual - data_color:

    df %>% 
      gt() %>% 
      data_color(
        columns = c("res1", "res2"),
        colors = c("green", "red"),
        apply_to = "fill",
        autocolor_text = FALSE)
    

    enter image description here