R-Shiny DT:动态亮点

问题描述

我正在尝试使用闪亮的DT表,该表可由用户编辑。 应该按照一些规则突出显示单元格(在这种情况下,当“ new”等于0或1时,将突出显示V1单元格。)

但是,我不能使其动态地工作:当用户编辑值时,突出显示的单元格保持不变。 我应该使用反应式吗?

这是我的短代码

library(shiny)
library(DT)

shinyApp(
  ui = fluidPage(DTOutput('tbl')),server = function(input,output) {

df = as.data.frame(cbind(matrix(round(rnorm(50),3),10)))
df$new=rownames(df)
    
    output$tbl=   renderDataTable({
      
      datatable(df,editable = T)%>% 
        formatStyle(
        'V1','new',backgroundColor = styleEqual(c(0,1),c('gray','yellow'))
      )
      
      })

谢谢您的帮助!

解决方法

尝试使df成为反应式,并通过input$tbl_cell_edit访问修改后的值。右侧的第二个表仅显示df中的第二个变量。它将显示对变量V2的所有更新。见下文

  library(shiny)
  library(DT)


    ui = fluidPage(
      fluidPage(
        column(8,DTOutput('tbl') ),column(3,DTOutput('tb2') )
      ))

    server = function(input,output) {
      DF1 <- reactiveValues(data=NULL)

      observe({
        df <- as.data.frame(cbind(matrix(round(rnorm(50),3),10)))
        names(df) <- c("V1","V2","V3","V4","V5")
        df$new=rownames(df)
        rownames(df) <- NULL
        DF1$data <- df
      })  

      output$tbl <-  renderDT({
        plen <- nrow(DF1$data)
        datatable(DF1$data,class = 'cell-border stripe',options = list(dom = 't',pageLength = plen,initComplete = JS(
                    "function(settings,json) {","$(this.api().table().header()).css({'background-color': '#000','color': '#fff'});","}")),editable = TRUE) %>%
            formatStyle('V1','new',backgroundColor = styleEqual(c(0,1),c('gray','yellow'))
            )

      })
      
      observeEvent(input$tbl_cell_edit,{
        info = input$tbl_cell_edit
        str(info)
        i = info$row
        j = info$col # + 1  # column index offset by 1
        v = info$value
        
        DF1$data[i,j] <<- DT::coerceValue(v,DF1$data[i,j])
      })
      
      output$tb2 <- renderDT({
        df2 <- NULL
        df2$Var1 <- DF1$data[,2]
        plen <- nrow(df2)
        df2 <- as.data.frame(df2)
        datatable(df2,"}")))
        
      })
      
    }

    shinyApp(ui,server)

output