Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color differently positive and negative values of DT::Datatable

Tags:

javascript

r

dt

I am trying to color the positive and negative values of a certain column (third) of a DT::Datatable with green and red colors respectively based on this code chunk, but I am not a javascript user. Is there any way to set this?

library(DT)

datatable(head(iris)) %>% 
    formatStyle(1:4, color = JS("value % 1 === 0 ? 'red' : ''"))
like image 359
firmo23 Avatar asked Sep 15 '25 15:09

firmo23


1 Answers

You can use DT::styleInterval for this:

library(DT)

## data (iris dataset contains no negative values)
dat <- data.frame(
    letters = LETTERS[1:26],
    numbers = sample(c(-1, -0.5, 0, 0.5, 1), 26, replace = TRUE)
)

datatable(dat) %>%
    formatStyle(
        columns = "numbers", 
        color = styleInterval(cuts = 0, values = c("red", "green")),
        fontWeight = "bold"
    )

dt_img


NB: If zero values should be ignored, you can set a black color to a small region around zero:

eps <- 1E-5

datatable(dat) %>%
    formatStyle(
        columns = "numbers", 
        color = styleInterval(cuts = c(-eps, eps), values = c("red", "black", "green")),
        fontWeight = "bold"
    )
like image 114
Joris C. Avatar answered Sep 18 '25 07:09

Joris C.