Conditional formatting cell in DataTable in R

11.9k views Asked by At

I have the following code so far as an example:

library(DT)

datatable(iris, options = list(pageLength = 5)) %>%
  formatStyle(
    'Sepal.Width',
    backgroundColor = styleInterval(3, c('gray', 'yellow'))
)

I am interested though in highlighting only a specific "cell" based on a condition.

For example if iris[3, 2] > 3.1 then background colour should be yellow.

for reference http://rstudio.github.io/DT/

sessionInfo() DT_0.1

1

There are 1 answers

0
nnn On BEST ANSWER

You can do this with the DT Helper Functions. There is a function to style the cells for certain intervals (styleInterval()) or if the cell value is equal to something with (styleEqual()). It doesn't seem that styleEqual() supports the direct input of a condition, but you could calculate the condition first (maybe make another column for it) and use it then.

As described on the page linked above (under section 2 "Style Table Cells") you can do it for example like this:

datatable(iris) %>% 
  formatStyle('Sepal.Length', fontWeight = styleInterval(5, c('normal', 'bold'))) %>%
  formatStyle(
    'Sepal.Width',
    color = styleInterval(c(3.4, 3.8), c('white', 'blue', 'red')),
    backgroundColor = styleInterval(3.4, c('gray', 'yellow'))
  ) %>%
  formatStyle(
    'Petal.Length',
    background = styleColorBar(iris$Petal.Length, 'steelblue'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  ) %>%
  formatStyle(
    'Species',
    transform = 'rotateX(45deg) rotateY(20deg) rotateZ(30deg)',
    backgroundColor = styleEqual(
      unique(iris$Species), c('lightblue', 'lightgreen', 'lightpink')
    )
  )