rstudio / DT

R Interface to the jQuery Plug-in DataTables
https://rstudio.github.io/DT/
Other
596 stars 182 forks source link

change one column color based on value from three different columns #925

Open rix206 opened 3 years ago

rix206 commented 3 years ago

How do I change one column color based on value from three diff columns? I tried this :

dt_d9=datatable(d9, editable = 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis'))) %>% formatStyle( 'R/Y/G', c('R','Y','G'), backgroundColor = styleInterval(c(2000000, 2500000), c('green', 'yellow', 'red'))

But it doesn't work. The condition is if 'G' value < = 2000000, then R/Y/G is green if 'Y' value >2000000 and <= 2500000 then R/Y/G is yellow and if 'R' value >2500000 then then R/Y/G is red. 'R', 'Y', 'G' are 3 diff columns

philibe commented 2 years ago

It's more a question for stackoverflow.

Below 2 answers with not the same result (I'm not sure which result is asked because of lack of information).

(datatable(head(iris) 

)
  %>% formatStyle( 
    columns = c("Petal.Length","Sepal.Width","Sepal.Length"),
    valueColumns =  c("Petal.Length","Sepal.Width","Sepal.Length"),
    target='cell',
    backgroundColor = styleInterval(c(1.4, 3), 
                                    c('green', 'yellow', 'red')
    )
  )
)

or

(datatable(head(iris) 
           %>% mutate(mytest= ifelse(Petal.Length<1.4,'G',ifelse(Sepal.Width>=1.4 & Sepal.Width<3,'Y',ifelse(Sepal.Length>5,'R',''))))
)
  %>% formatStyle( 
    columns = c("Petal.Length","Sepal.Width","Sepal.Length"),
    valueColumns =  c("mytest"),
    target='cell',
    backgroundColor = styleEqual(c('G','Y','R'), 
                                    c('green', 'yellow', 'red')
    )
  )
)