I have a DT data table which contain strings like below:
I want to change the colour of the cell, so that the cells with strings that contain "OK" will turn green, and cells with strings that contain "ERROR" will turn red. I know that I can change the cell colour by using formatStyle
and styleEqual
but it does not seem to work when matching string patterns.
CodePudding user response:
library(DT)
render <- c(
"function(data, type, row){",
" if(type === 'display'){",
" var color = /OK$/.test(data) ? 'green' : (/ERROR$/.test(data) ? 'red' : 'black');",
" data = '<span style=\"color: ' color ';\">' data '</span>';",
" }",
" return data;",
"}"
)
dat <- data.frame(
a = c("1 - OK", "1 - ERROR", "2 - ERROR"),
b = c("3 - ERROR", "2 - OK", "3 - OK")
)
datatable(
dat,
options = list(
columnDefs = list(
list(targets = c(1, 2), render = JS(render))
)
)
)