Search code examples
rdatatable

How to conditionally add colors in datatable with R?


In a datatable with R, I'd like to display the values of columns "val1" and "val2" in red.

If these values are more than twice greater than or more than twice less than the value of "mymean" for each each row.

Example:

library(tibble)
library(DT)

mydf <- tribble(
  ~x,  ~mymean, ~val1, ~val2,
  "a", 3, 2, 8,
  "b", 5, 6, 1
)
# Using formatStyle() ?
datatable(mydf) |> 
  formatStyle(
    c("val1","val2"),
    color = "red"
  )

Many thanks in advance!


Solution

  • You can add two columns which contain the information whether the value is in the desired interval or not. Then hide them in the datatable command in the columnDefs and use styleEqual in formatStyle to define the colors:

    library(tibble)
    library(DT)
    library(dplyr)
    
    mydf <- tribble(
      ~x,  ~mymean, ~val1, ~val2,
      "a", 3, 2, 8,
      "b", 5, 6, 1
    )
    
    mydf <- mydf %>% mutate(val_1_in_interval = ifelse(val1 >= 0.5*mymean & val1 <= 2*mymean,1,0))
    mydf <- mydf %>% mutate(val_2_in_interval = ifelse(val2 >= 0.5*mymean & val2 <= 2*mymean,1,0))
    
    datatable(mydf,options = list(columnDefs = list(list(visible = FALSE,targets = c(5,6))))) |> 
      formatStyle(c("val1","val2"),c("val_1_in_interval","val_2_in_interval"),color = styleEqual(c(0,1),c('red','black')))