如何根据另一列中的单元格更改闪亮 DT::dataTable 中单元格的颜色?

How to change color of cells in a DT::dataTable in shiny, based on cells in another column?

我是 shiny/r 的新手,正在尝试根据另一个单元格的值更改单元格 (DT table) 的背景颜色。我尝试使用 https://rstudio.github.io/DT/010-style.html

中的示例
datatable(df) %>% formatStyle(
  'V1', 'V6',
  backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
)

但不知何故它似乎对我不起作用

这是我的代码:

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

我不确定我做错了什么。也许它在错误的地方,我不知道。此外,如果我需要根据三个不同的列(R、Y、G)更改列 'R/Y/G' 的颜色,基于动态输入(不像 0 和 1 那样硬编码)=,我将如何实现? 谢谢

P.S。 如果我添加此代码

dt_d9=datatable(d9) %>% formatStyle(
'R/Y/G', 'Y',
backgroundColor = styleEqual(c(0, 1), c('red', 'yellow'))
)

并替换

output$x9 = render_dt(d9, 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis')))

output$x9 = render_dt(dt_d9, 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis')))

我确实得到了 R/Y/G 列的颜色,但编辑单元格功能停止工作。可以在此处找到编辑单元格功能:https://yihui.shinyapps.io/DT-edit/

您的代码出现以下错误:

renderDataTable ignores ... arguments when expr yields a datatable object;

因为你现在 return DT::datatable 对象 renderDT 而不是数据框。这有点类似于。所以现在你必须将所有参数移动到 DT::datatable 构造函数:

render_dt = function(data) {
 renderDT(data)
}

  dt_d9 <- datatable(d9, editable = 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis'))) %>% 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'))
 )

 output$x9 = render_dt(dt_d9)