I want to highlight cells in a datatable on the condition that the values are contained in another list.
Here is my reproducible example:
library(DT)
library(tidyverse)
df_table <- tibble(
id = 1:10,
V1 = rnorm(10)
)
my_id_list <- c(4, 6, 8)
datatable(df_table)
Now I want to highlight the id
values which are contained in the my_id_list
:
The following code does not work, but should clarify my intention:
datatable(df_table) %>%
formatStyle("id", backgroundColor = if(id %in% my_id_list) {"yellow"})
I am unsure whether a solution can be achieved with the help of R. Probably a solution with javascript makes the most sense, as shown in this issue:
Implementing ifelse (or if_else) in datatable output to conditionally change the background color of a reactive table (shiny and r)
You can create an extra column with binary coding, then using styleEqual
to match on the binary column, but hide it in the actual DT table.
Reference from https://rstudio.github.io/DT/010-style.html
library(DT)
library(dplyr)
datatable(data = df_table |> mutate(col = ifelse(id %in% my_id_list, 0, 1)),
options = list(columnDefs = list(list(targets = 3, visible = FALSE)))) |>
formatStyle("id", "col", backgroundColor = styleEqual(c(0, 1), c("yellow", "")))