1

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: enter image description here

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)

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
TobKel
  • 1,293
  • 8
  • 20
  • Add a column `color = c("", "", "","yellow", "", "yellow", "", "yellow", "", "")` to your table. Then use `formatStyle` using `"color"` as the `valueColumns` argument. Finally hide this extra column for the rendering. – Stéphane Laurent May 25 '23 at 08:49
  • @StéphaneLaurent Unfortunately I can't create a solution on my dataset from your comment. Could you post a solution as an answer below? – TobKel May 25 '23 at 09:15

1 Answers1

1

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

DT

benson23
  • 16,369
  • 9
  • 19
  • 38