0

I'm trying to color the row in Datatable when two of the columns meet certain conditions. I have created a 'dummy' variable to do so with the use of formatStyle function but I don't want the 'dummy' column to be visible.

iris %>% 
  mutate(condition = (Sepal.Length < 5.0 | Petal.Length < 3.0) * 1) %>% 
  datatable() %>%
  formatStyle("condition", target = 'row', 
              backgroundColor = styleEqual(c(1, 0), c('red', 'white')))

enter image description here

I've tried to do the similar thing with the use of javascript but it doesn't work (no table is rendered):

script <- "
function( row, aData ) {
      if ( parseFloat(aData[0]) < 5.0 && parseFloat(aData[2]) < 3.0)
        $('td:eq(x), row).css('background-color', '#FC4A4A');
      else 
        $('td:eq(x), row)css('background-color', '#F2E8E8');
  }
"

iris %>% 
  datatable(options = list(rowCallback = JS(script)))
potockan
  • 3,998
  • 3
  • 25
  • 37

1 Answers1

2

Thanks to this I found the solution:

iris %>% 
  mutate(condition = (Sepal.Length < 5.0 | Petal.Length < 3.0) * 1) %>% 
  datatable(list(columnDefs = list(list(visible = FALSE, targets = c(6))))) %>% #hiding the 6th column
  formatStyle("condition", target = 'row', 
              backgroundColor = styleEqual(c(1, 0), c('red', 'white')))
potockan
  • 3,998
  • 3
  • 25
  • 37