www
www

Reputation: 39154

How to color the background of a cell in datatable (DT package) in R with column and row names or indices?

Here is an example. I created a data frame and use that to create a datatable for visualization. As you can see, my column name and the row from the first column indicate conditions from A and B. What I want to do is to change the background color of a specific cell in this datatable. It is easy to select the column to change, as explained in this link (https://rstudio.github.io/DT/010-style.html). However, it is not obvious to me how to specify the row I want to select.

To give you more context, I am developing a Shiny app, and I would like to design a datatable allow me to color a cell based on the condition from A and B. For example, if A is less than 1 and B is between 1 and 2, I would like to be able to select the second cell from the A is less than 1 column. To acheive this, I will need to know how to specify the row number or row name. For now, I only know how to specify the rows based on the contents in the rows, as this example shows.

library(tibble)
library(DT)

dat <- tribble(
  ~`A/B`,                ~`A is less than 1`, ~`A is between 1 and 2`,  ~`A is larger than 2`,
  "B is less than 1",                    10,                      30,                     30,
  "B is between 1 and 2",                 20,                      10,                     30,
  "B is larger than 2",                   20,                      20,                     10
)


datatable(dat, filter = "none", rownames = FALSE, selection = "none",
          options = list(dom = 't', ordering = FALSE)) %>% 
  formatStyle(
  'A is less than 1',
   backgroundColor = styleEqual(20, "orange")
)

enter image description here

Upvotes: 2

Views: 4051

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84519

I'm not sure to get the question, but if you want to change the background color of a cell given by its row index and its column index (that's what I understand), you can do:

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(dat, 
          options = list(
            dom = "t",
            rowCallback = JS(changeCellColor(1, 2))
          )
)

Upvotes: 7

Related Questions