代码之家  ›  专栏  ›  技术社区  ›  Vlad

R DT-编辑表格中的值

  •  16
  • Vlad  · 技术社区  · 8 年前

    是否可以通过编辑DT::DataTable来更新反应式数据源?下面的代码是基于 this code 随着x变成反应性的变化。当试图在observeEvent中更改x时,问题就开始了。

    使用x reactive的目的是,我打算从外部数据库中获取它,然后将对DT::DataTable的编辑写回数据库,以便它与用户看到的内容保持同步(我可以这么做——这不是问题的一部分)。

    library(shiny)
    library(DT)
    shinyApp(
      ui = fluidPage(
        DTOutput('x1')
      ),
      server = function(input, output, session) {
        x = reactive({
          df <- iris
          df$Date = Sys.time() + seq_len(nrow(df))
          df
        })
        output$x1 = renderDT(x(), selection = 'none', editable = TRUE)
    
        proxy = dataTableProxy('x1')
    
        observeEvent(input$x1_cell_edit, {
          info = input$x1_cell_edit
          str(info)
          i = info$row
          j = info$col
          v = info$value
    
          # problem starts here
          x()[i, j] <<- isolate(DT::coerceValue(v, x()[i, j])) 
          replaceData(proxy, x(), resetPaging = FALSE)  # important
        })
      }
    )
    
    2 回复  |  直到 8 年前
        1
  •  9
  •   SeGa    8 年前

    我不确定我是否理解正确,但这个解决方案可能会对你有所帮助。我把你的reactiveValues对象改成了reactiveValues对象,删除了replaceData行。

    library(shiny)
    library(DT)
    shinyApp(
      ui = fluidPage(
        DTOutput('x1'),
        verbatimTextOutput("print")
      ),
      server = function(input, output, session) {
        x = reactiveValues(df = NULL)
    
        observe({
          df <- iris
          df$Date = Sys.time() + seq_len(nrow(df))
          x$df <- df
        })
    
        output$x1 = renderDT(x$df, selection = 'none', editable = TRUE)
    
        proxy = dataTableProxy('x1')
    
        observeEvent(input$x1_cell_edit, {
          info = input$x1_cell_edit
          str(info)
          i = info$row
          j = info$col
          v = info$value
    
          # problem starts here
          x$df[i, j] <- isolate(DT::coerceValue(v, x$df[i, j]))
        })
    
        output$print <- renderPrint({
          x$df
        })
      }
    )
    
        2
  •  1
  •   Tushar Walzade    7 年前

    如果在DT中没有显示行名称,那么应该在 info$col 要获得正确的列,即:。, j = info$col + 1 .