DT icon indicating copy to clipboard operation
DT copied to clipboard

Color cells based on value from another column value

Open rix206 opened this issue 4 years ago • 0 comments

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 https://rstudio.github.io/DT/010-style.html

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'),
)

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')))

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

P.S. 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 : https://yihui.shinyapps.io/DT-edit/

rix206 avatar Aug 11 '21 06:08 rix206