1

I want a way to color multiple cells in a data table if given their row and column indexes. I have found the solution from here. But here the function can colour only 1 cell. I want it to be modified, so that it takes a vector of row and column indexes as argument and colour them. Any help is highly appreciated. I am attaching the code snippet below.

changeCellColor <- function(row, col){
  c(
    "function(row, data, num, index){",
    sprintf("  if(index == %d){", row-1),
    sprintf("    $('td:eq(' + %d + ')', row)", col),
    "    .css({'background-color': 'orange'});",
    "  }",
    "}"  
  )
}
datatable(iris, 
          options = list(
            dom = "t",
            rowCallback = JS(changeCellColor(1, 2))
          )
)
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225

1 Answers1

3

Is it what you want ?

library(DT)

changeCellsColor <- function(rows, cols){
  stopifnot(length(rows) == length(cols))
  c(
    "function(row, data, num, index){",
    sprintf("  var rows = [%s];", paste0(rows-1, collapse = ",")),
    sprintf("  var cols = [%s];", paste0(cols, collapse = ",")),
    "  for(var i = 0; i < rows.length; ++i){",
    "    if(index == rows[i]){",
    "      $('td:eq(' + cols[i] + ')', row)",
    "        .css({'background-color': 'orange'});",
    "    }",
    "  }",
    "}"
  )
}
datatable(iris,
          options = list(
            dom = "t",
            rowCallback = JS(changeCellsColor(c(1,3), c(2,1)))
          )
)
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225