R Shiny DT - 用 react 编辑表中的值

标签 r shiny dt

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

让 x react 的目的是我打算从外部数据库中获取它,然后将 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
    })
  }
)

最佳答案

我不确定我是否正确理解您,但也许这个解决方案可能对您有所帮助。我将您的 react 更改为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
    })
  }
)

关于R Shiny DT - 用 react 编辑表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50470097/

相关文章:

r - 如何在 DT 数据表行中选择 html 选择输入小部件? R

r - 从R中的嵌入列表中提取向量

r - 如何定义 R 函数的参数类型?

替换 dplyr 中的 plyr::cbind.fill?

html - 浏览器选项卡中的标题在 Shiny 的仪表板页面中为空

c - 在 shiny 中使用 .C

R Shinydashboardplus Flipbox - 如何删除图像

r - 数据表 {DT} : How to format columns in PDF export?

r - 使用 R DataTable 包添加加载微调器

r - as.Date 不保留 R 中的时间