Search code examples
rreactable

In R reactable package how to color cell with lag values being greater than actual value?


This is my code:

library(tidyverse)
library(reactable)

reactable(
    iris,
    columns = set_names(x = colnames(iris)) %>% 
        map(~ {
            colDef(
                style = function(value) {
                    ds_color <- ifelse(lag(value) < value , "green", "white")
                    list(background = ds_color)
                }
            )
        })
)

What I need is to color the background of the cell when the value on the row is greater than the lag value.


Solution

  • Unfortunately only the cell value is passed to the style function, not a whole vector. Hence, using lag will not work.

    However, besides the cell value it's also possible to pass the row index and the column name which could be used to achieve your desired result like so:

    library(tidyverse)
    library(reactable)
    
    reactable(
      iris,
      columns = set_names(x = colnames(iris)[-5]) %>% 
        map(~ {
          colDef(
            style = function(value, index, name) {
              ds_color <- if (index > 1 && iris[index - 1, name] < iris[index, name]) {
                "green"
              } else {
                "white"
              }
              list(background = ds_color)
            }
          )
        })
    )
    

    enter image description here