I am new to shiny/r and trying to change the background color of a cell (DT table) base on value of another cell. I tried using this example from More Examples on Styling Cells, Rows, and Tables
datatable(df) %>% formatStyle(
'V1', 'V6',
backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
)
But somehow it doesn't seem to work for me
Here's my code :
dt_output = function(title, id) {
fluidRow(column(
12, h1(paste0(title)),
hr(), DTOutput(id)
))
}
render_dt = function(data, editable = 'cell', server = TRUE, ...) {
renderDT(data, selection = 'none', server = server, editable = editable, ...)
}
ui = fluidPage(
downloadButton("mcp_csv", "Download in CSV", class="but"),
dt_output('Cantilever/Membrane Probe Report', 'x9'),
#dt_output('Cantilever/Membrane with Selective Column Edit', 'x10')
)
server = function(input, output, session) {
d1 = readRDS("cmp.rds")
d9 = d1
output$x9 = render_dt(d9, 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis')))
#output$x10 = render_dt(d10, list(target = 'row', disable = list(columns = c(0, 1, 2, 3))))
when the table doesn't contain row names
observeEvent(input$x9_cell_edit, {
d9 <<- editData(d9, input$x9_cell_edit, 'x9', rownames = FALSE)
saveRDS(d9, 'cmp.rds', version = 2)
})
datatable(d9) %>% formatStyle(
'R/Y/G', 'Y', #'R/Y/G' is the column cell I'm trying to change values for based on column 'Y'
backgroundColor = styleEqual(c(0, 1), c('red', 'yellow'))
)
I'm not sure what I'm doing wrong. Maybe it's in the wrong place, I don't know. Also if I needed to change color of column 'R/Y/G' based on three different columns (R, Y, G), based on dynamic input (not hardcoded like 0 and 1) =, how would I implement that?
Thanks
Update :
If I add this code
dt_d9=datatable(d9) %>% formatStyle(
'R/Y/G', 'Y',
backgroundColor = styleEqual(c(0, 1), c('red', 'yellow'))
)
and replace
output$x9 = render_dt(d9, 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis')))
with
output$x9 = render_dt(dt_d9, 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis')))
I do get the colors on the R/Y/G column, but the edit cell function stops working. The edit cell function can be found here : Double-click to edit table cells