R Shiny DT - edit values in table with reactive

戏子无情 提交于 2019-11-28 00:27:36

问题


Is it possible to update a reactive data source by editing the DT::DataTable? Below code is based on this code with change that x is made reactive. The problem starts when trying to change x in observeEvent.

The purpose of having x reactive is that I intend to source it from an external database, then have edits to the DT::DataTable write back to the database so that it stays in sync with what the user sees (I'm fine with doing that - it is not part of the question).

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

回答1:


I am not sure if I understand you correctly, but maybe this solution might help you a bit. I changed your reactive into a reactiveValues object and I removed the replaceData line.

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:


If you don't show the row names in your DT then you should add 1 to info$col to get the correct column i.e., j = info$col + 1.



来源:https://stackoverflow.com/questions/50470097/r-shiny-dt-edit-values-in-table-with-reactive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!