编辑数据表单元格值后立即更改单元格颜色 R shiny

Change color of cells as soon as datatable cell value is edited R shiny

我试图在 'R'、'Y' 或 'G' 列的值更改后立即更改 'R/Y/G' 列的单元格颜色。出于这个原因,我已经使数据表可编辑。颜色发生变化,但仅当我编辑单元格值并关闭应用程序并再次重新打开时才会发生变化。但只要我编辑单元格值,它就不会改变。 这是我的代码:

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 as CSV", class="but"),
  
  dt_output('Report', 'x9')
)

server = function(input, output, session) {
  d1 = readRDS("cmp.rds")
  d9 = d1
  
  observeEvent(input$x9_cell_edit, {
    d9 <<- editData(d9, input$x9_cell_edit, 'x9', rownames = FALSE)
    saveRDS(d9, 'cmp.rds', version = 2)
  })
  
  d9$tcolor <- ifelse(d9$R > 2500000, 2,
                      ifelse(d9$Y > 2000000 & d9$Y <= 2500000, 0,
                             ifelse(d9$G <= 2000000, 1)))
  
  dt_d9=datatable(d9, editable = 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis'))) %>% formatStyle(
    'R/Y/G', 'tcolor',
    backgroundColor = styleEqual(c(0,1,2), c('yellow', 'green', 'red')),fontWeight = 'bold'
  )
  
  output$x9 = render_dt(dt_d9)

基于想法,这是服务器部分,将数据帧存储在reactiveValues():

server = function(input, output, session) {
  d1 = readRDS("cmp.RDS")
  d9 = d1
 
  d9$tcolor <- NA
  rv <- reactiveValues()
  observe({
    rv$d9 <- d9
  })
  
  dt_d9=datatable(isolate(d9), editable = 'cell', rownames = FALSE, extensions = 'Buttons', options = list(dom = 'Bfrtip', buttons = I('colvis'))) %>% formatStyle(
    'R/Y/G', 'tcolor',
    backgroundColor = styleEqual(c(0,1,2), c('yellow', 'green', 'red')),fontWeight = 'bold'
  )
  
  output$x9 = render_dt(dt_d9)

  proxy = dataTableProxy('x9')
  observe({
    DT::replaceData(proxy, rv$d9, rownames = FALSE, resetPaging = FALSE)
  })
  
  observeEvent(input$x9_cell_edit, {
    rv$d9 <<- editData(rv$d9, input$x9_cell_edit, 'x9', rownames = FALSE)
    d9 <- rv$d9
    d9$tcolor <- ifelse(d9$R > 2500000, 2,
                        ifelse(d9$Y > 2000000 & d9$Y <= 2500000, 0,
                               ifelse(d9$G <= 2000000, 1)))
    rv$d9 <<- d9
    saveRDS(d9, 'cmp.rds', version = 2)
    
  })
  
}