Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional formatting cell in DataTable in R

Tags:

r

dt

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

like image 533
dimitris_ps Avatar asked Jun 09 '15 21:06

dimitris_ps


1 Answers

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')
    )
  )
like image 91
nnn Avatar answered Oct 31 '22 17:10

nnn