Reputation: 387
I have a data.table
with 3 columns.
trial <- matrix(c(3,4,1,2,1,2,4,2,5), ncol=3)
colnames(trial) <- c('value', 'min', 'max')
trial.table <- data.table(trial)
Using R (Shiny and DT), I would like to change the font color of the column value based on the min and max range.
I am trying to use this:
datatable(trial.table, rownames = FALSE) %>%
formatStyle('value', color = styleInterval(c(trial.table$min,trial.table$max), c('orange', 'green', 'red')))
But It gives me back:
Error in styleInterval(c(trial.table$min, trial.table$max), c("orange", :
length(cuts) must be equal to length(values) - 1
The result should be:
Column "value" with the values: 3 with color green, 4 with color red and 1 with color orange.
It works if instead c(trial.table$min,trial.table$max)
we use numbers - c(1,2)
...
Thanks a lot!
Upvotes: 2
Views: 2571
Reputation: 387
The solution is use rowCallback instead styleInterval.
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[1]) < aData[2])
$("td:eq(1)", nRow).css("color", "orange");
if (parseFloat(aData[1]) <= aData[3] && parseFloat(aData[1]) >= aData[2])
$("td:eq(1)", nRow).css("color", "green");
if (parseFloat(aData[1]) > aData[3])
$("td:eq(1)", nRow).css("color", "red");
}')))
Upvotes: 2