Incorporating conditional formatting into a Shiny app datatable with rowCallback options poses a challenge due to the dynamic nature of table size changes. The aim is to change the background color based on whether values in certain columns meet specific conditions. One approach involves utilizing a for loop to define which columns should be formatted.
Manually specifying the columns for conditional formatting works well:
if (!require(devtools)) install.packages("devtools"); library(devtools)
if (!require(DT)) devtools::install_github("rstudio/DT"); library(DT)
trial <- matrix(c(3,4,1,2,1,2,4,2,5), ncol=3)
colnames(trial) <- c('value', 'min', 'max')
trial.table <- data.frame(trial)
DT::datatable(trial.table,options = list(rowCallback = JS('
function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
if (parseFloat(aData[2]) > aData[1])
$("td:eq(2)", nRow).css("background-color", "orange");
if (parseFloat(aData[2]) > aData[1])
$("td:eq(3)", nRow).css("background-color", "orange");
}')))
Attempting to apply a similar logic using a loop leads to a blank display:
DT::datatable(trial.table,options = list(rowCallback = JS('
function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
for (i =2, i < 4, i++) {
if (parseFloat(aData[i]) > aData[1])
$("td:eq(i)", nRow).css("background-color", "orange");
}
}')))
Is it possible to use for loops effectively within Javascript in R?