R 闪亮 DT - 使用反应式编辑表中的值



是否可以通过编辑 DT::D ataTable 来更新反应式数据源? 下面的代码基于此代码,更改了 x 是响应式的。 当尝试在 observeEvent 中更改 x 时,问题就开始了。

让 x 反应式的目的是我打算从外部数据库获取它,然后编辑 DT::D ataTable 写回数据库,以便它与用户看到的内容保持同步(我这样做很好 - 这不是问题的一部分(。

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

我不确定我是否正确理解您,但也许此解决方案可能会对您有所帮助。我将您的反应式对象更改为反应式值对象,并删除了替换数据行。

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

如果您没有在 DT 中显示行名,那么您应该在info$col中添加 1 以获得正确的列,即j = info$col + 1.

最新更新