Jacob
Jacob

Reputation: 63

Change DT font color conditionally by value in R

Here is a minimal example of the datatable I'm working with:

dt <- DT::datatable(data.frame('V1' = c(3,2,-1), 'V2' = c(3,-1,-7), 'V3' = c(3, -5,-12)))

I would like to change the font color to red for all negative values. I've experimented with styleEquals and styleInterval, but I don't see a way to set a conditional test, e.g., value < 0.

I've tried the JS function, but I'm not so familiar with javascript, and this code doesn't produce a table:

dt %>% formatStyle(columns = 1:3, color = JS("value < 0 ? 'red'"))

This table will be rendered in a shiny app.

Upvotes: 3

Views: 1523

Answers (1)

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

Reputation: 84719

Like this:

dt %>% formatStyle(1:3, color = styleInterval(0, c("red", "black")))

Upvotes: 3

Related Questions