Reputation: 398
In my DT, I am trying to create conditional formatting for each cell, where formatting is based on different rules for each row. The goal is to create an easy visual comparison between column 1 and column 2
For example
If [1,1] < [1,2] highlight [1,1] green & [1,2] red
If [2,1] < [2,2] highlight [2,1] red & [2,2] green
19 March update: For ease, I built a "winner" column in R, and am trying to compare the data in the table against that column.
library(DT)
example.data <- data.frame(col.1 = rep(1, 2),
col.2 = rep(2, 2),
winner = c(1,2))
datatable(example.data,
options = list(
rowCallback = JS(
'function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
if (parseFloat(aData[3] = 1)){
$("td:eq(1)", nRow).css("background-color", "green");
}
if (parseFloat(aData[3] = 2)){
$("td:eq(1)", nRow).css("background-color", "red");
}
if (parseFloat(aData[3] = 1)){
$("td:eq(2)", nRow).css("background-color", "red");
}
if (parseFloat(aData[3] = 2)) {
$("td:eq(2)", nRow).css("background-color", "green");
}
}'
)
))
The above code turns column 1 red and column 2 green. Any help would be appreciated.
Upvotes: 0
Views: 586
Reputation: 398
The errors in the previous code were due to the misuse of the = operator, should have been ==, and passing the argument as a floating point using parseFloat. For anyone trying to do a similar task, the following example should work.
datatable(example.data,
options = list(
rowCallback = JS(
'function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
if (aData[3] == "1"){
$("td:eq(1)", nRow).css("background-color", "green");
}
if (aData[3] == "2"){
$("td:eq(1)", nRow).css("background-color", "red");
}
if (aData[3] == "1"){
$("td:eq(2)", nRow).css("background-color", "red");
}
if (aData[3] == "2") {
$("td:eq(2)", nRow).css("background-color", "green");
}
}'
)
))
Upvotes: 1