1

I am trying to apply conditional formatting to one row of a datatable, using styleInterval (within formatStyle of the DT package). All the examples I have found online have either been for formatting the whole datatable, restricting the columns involved, or formatting entire rows based on the values in a single column.

I want to restrict the rows involved to just the first row ('entity1') in the example below.

entity <- c('entity1', 'entity2', 'entity3')
value1 <- c(21000, 23400, 26800)
value2 <- c(21234, 23445, 26834)
value3 <- c(21123, 234789, 26811)
value4 <- c(27000, 23400, 26811)
entity.data <- data.frame(entity, value1, value2, value3, value4)

DT::datatable(entity.data) %>%
  formatStyle(columns = 2:5,
              backgroundColor = styleInterval(cuts = c(21200,22000),
                                              values = c('red','white','green')))

Am I missing the way to do this using formatStyle or do I need to approach this with another function/package? Thanks!

Sean Slavin
  • 56
  • 10

1 Answers1

5

Use a rowCallback:

library(DT)

entity <- c('entity1', 'entity2', 'entity3')
value1 <- c(21000, 23400, 26800)
value2 <- c(21234, 23445, 26834)
value3 <- c(21123, 234789, 26811)
value4 <- c(27000, 23400, 26811)
entity.data <- data.frame(entity, value1, value2, value3, value4)

rowCallback <- c(
  "function(row, dat, displayNum, index){",
  "  if(index == 0){",
  "    for(var j=2; j<dat.length; j++){",
  "      var x = dat[j];",
  "      var color = x <= 21200 ? 'red' : x <= 22000 ? 'white' : 'green';",
  "      $('td:eq('+j+')', row)", 
  "        .css('background-color', color);",
  "    }",
  "  }",
  "}"
)

datatable(entity.data, 
          options = 
            list(rowCallback = JS(rowCallback))
)

enter image description here

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • would you mind to help me at https://stackoverflow.com/questions/70955804/implementing-ifelse-or-if-else-in-datatable-output-to-conditionally-change-the ? I'm trying to implement this code to a close problem – Luis Feb 02 '22 at 13:00