With code below (from this link), we can set background colors for the cells of multiple columns based on string contents using gt
package:
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() %>%
data_color(
columns = c("res1", "res2"),
colors = c("green", "red"),
apply_to = "fill",
autocolor_text = FALSE)
Out:
Now let's say I will need to set red background color only if content is true
for columns res1
and res2
, if it's other values such as false
or NA
, just keep as original, which means I hope to highlight true
cells for these two columns. How could I do that? Thanks.
References: