'DT package Color the background of the cells according to a double conditionality
I have a problem to finish my DT on R. The colors appear according to ranges of values. For the DD column, when the value is between -3 and +3, the cell is orange. However, I would like when the values of D and DD are 0, the cell in DD appears dark green, not orange.enter image description here
Here is my script :
#color cells
datatable(data = t,rownames = F, filter = 'top',extensions = 'Buttons', options = list(
dom = 'Bfrtip',
pageLength=20,
buttons = c('copy', 'excel', 'pdf'))) %>%
formatStyle('EE',
backgroundColor=styleInterval(cuts=c(250,500,750,1000,1500),
values=c('darkgreen','lightgreen','yellow','orange','pink','red')))%>%
formatStyle('PJFA',
backgroundColor=styleInterval(cuts=c(3.9,5.1),values=c('red','orange','darkgreen'))) %>%
formatStyle('DEE',
backgroundColor=styleInterval(cuts=c(-201,201),values=c('darkgreen','orange','red')))%>%
formatStyle('DPJFN',
backgroundColor=styleInterval(cuts=c(-0.6,0,0.6),values=c('red','orange','lightgreen','darkgreen')))%>%
formatStyle('DPJFA',
backgroundColor=styleInterval(cuts=c(-0.6,0,0.6),values=c('red','orange','lightgreen','darkgreen'))) %>%
formatStyle('DD',
backgroundColor=styleInterval(cuts=c(-5,-3,3,5),values=c('darkgreen','lightgreen','orange','pink','red'))) %>%
formatStyle('DPJFN','Chgt_poste',
color = styleEqual(c('y','n'),values=c('white','black'))) %>%
formatStyle('NFR',
backgroundColor=styleInterval(cuts=c(1,3,5,7,8),values=c('darkred','red','pink','orange','lightgreen','darkgreen'))) %>%
formatStyle('NFJ',
backgroundColor=styleInterval(cuts=c(7,8,9,10,12),values=c('red','pink','orange','yellow','lightgreen','darkgreen'))) %>%
formatStyle('D',
backgroundColor=styleInterval(cuts=c(0.1,3,6,9,12),values=c('darkgreen','lightgreen','yellow','orange','pink','red')))
Solution 1:[1]
You can use styleInterval followed by styleEqual:
library(DT)
dat <- data.frame(
CC = c(7, 4, 6, 9, 2),
DD = c(-6, -4, -2, 0, 4)
)
datatable(
dat
) %>%
formatStyle(
"DD",
backgroundColor = styleInterval(
cuts = c(-5, -3, 3, 5),
values = c('darkgreen', 'lightgreen', 'orange', 'pink', 'red')
)
) %>%
formatStyle(
"DD",
backgroundColor = styleEqual(0, "blue")
)
EDIT
Following the comment, you have to do an hidden auxiliary column:
library(DT)
dat <- data.frame(
CC = c(7, 4, 6, 9, 2),
DD = c(-6, -4, -2, 0, 4),
D = c(0, 1, 2, 0, 3)
)
dat$hidden <- dat$DD == 0 & dat$D == 0
datatable(
dat,
options = list(
columnDefs = list(
list(targets = 4, visible = FALSE)
)
)
) %>%
formatStyle(
"DD",
backgroundColor = styleInterval(
cuts = c(-5, -3, 3, 5),
values = c('darkgreen', 'lightgreen', 'orange', 'pink', 'red')
)
) %>%
formatStyle(
"DD", "hidden",
backgroundColor = styleEqual(TRUE, "blue")
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

