R Shiny应用-在DT中编辑值并更新

时间:2019-02-21 16:22:22

标签: r shiny dt

我有一个闪亮的应用程序,其中的一项功能是允许用户编辑表中的值,当单击运行时,它将使用用户输入作为函数的值,然后更新同一表中的结果。下面是当前表和预期表的示例。因此,在第一个表中,如果用户更改了通道A和C的电流值并单击运行,则它应该将自身更新为表预期输出中反映的值。

所以我的问题是,是否可以将可编辑的DT值用作函数的输入。

library(shiny)
library(DT)
shinyApp(
  ui = fluidPage(
    DT::dataTableOutput("x1"),
    actionButton("opt_run", "Run"),
    tags$h1("Expected Output"),
    DT::dataTableOutput("x2")
  ),
  server = function(input, output, session) {

    df <- data.table(Channel = c("A", "B","C"),
                     Current = c("2000", "3000","4000"),
                     Modified = c("2500", "3500","3000"),
                     New_Membership = c("450", "650","700"))

    output$x1 = renderDT(df, selection = 'none', editable = TRUE)

    expdf <- data.table(Channel = c("A", "B","C"),
                     Current = c("3000", "3000","5000"),
                     Modified = c("3500", "3500","6000"),
                     New_Membership = c("650", "650","1100"))

    output$x2 = renderDT(expdf, selection = 'none', editable = TRUE)

    })
  }
)

1 个答案:

答案 0 :(得分:1)

我不确定您是否希望将它们存储在全局范围内。我将为您提供一个全局版本,以便您可以将其保存到数据库或磁盘上的某个位置:

您可以使用input$x1_cell_edit访问单元格值,请注意,我按F5刷新页面以检查值是否已保存

library(shiny)
library(DT)
options(stringsAsFactors = F)

df <- data.frame(Channel = c("A", "B","C"),
                 Current = c("2000", "3000","4000"),
                 Modified = c("2500", "3500","3000"),
                 New_Membership = c("450", "650","700"))

expdf <- data.frame(Channel = c("A", "B","C"),
                    Current = c("3000", "3000","5000"),
                    Modified = c("3500", "3500","6000"),
                    New_Membership = c("650", "650","1100"))

shinyApp(
  ui = fluidPage(
    DT::dataTableOutput("x1"),
    tags$h1("Expected Output"),
    DT::dataTableOutput("x2")
  ),
  server = function(input, output, session) {

    output$x1 = renderDT(df, selection = 'none', editable = TRUE)

    observeEvent(input$x1_cell_edit, {
      df[input$x1_cell_edit$row,input$x1_cell_edit$col] <<- input$x1_cell_edit$value
    })

    output$x2 = renderDT(expdf, selection = 'none', editable = TRUE)
    observeEvent(input$x2_cell_edit, {
      expdf[input$x2_cell_edit$row,input$x2_cell_edit$col] <<- input$x2_cell_edit$value
    })
  })
}
)

enter image description here