使用R Shiny应用程序的反应值中的数据编辑数据表

时间:2019-03-19 16:42:35

标签: r shiny dt

所以我有一个闪亮的应用程序,我想在其中编辑表中的值。现在,当我将实际数据df用于编辑表时,它可以工作。但是我想使用reactiveValuesv$data)中的数据来渲染表格并在单击重置时使用它。是否可以在数据表中使用反应性值。

library(shiny)
library(dplyr)
library(DT)

input_data <- data.frame(Channel = c("A", "B","C"),
                 lower_rate = c (.5, .5, .5),
                 lower_current = c(2000, 3000, 4000),
                 New_Membership = c(450, 650,700),
                 stringsAsFactors = FALSE) %>% 
  mutate(lower_bound = lower_current * lower_rate)

optimzation <- function(input, output, session, data,budget,run,reset) {

  v <- reactiveValues(data = data)

  observeEvent(run(), {
    v$data <- data %>% mutate(opt = lower_current * budget())
  })

  proxy = dataTableProxy("mod_table")

  observeEvent(input$mod_table_cell_edit, {
    info = input$mod_table_cell_edit
    str(info)
    i = info$row
    j = info$col
    k = info$value


    if (j %in% match(c("lower_rate", "lower_bound"), names(df))) {
      df[i, j] <<- DT::coerceValue(k, df[i, j])

      if (j %in% match("lower_bound", names(df))) {
        df$lower_rate <<- df$lower_bound / df$lower_current
      }
      if (j %in% match("lower_rate", names(df))) {
        df$lower_bound <<- df$lower_current * df$lower_rate
      }
    } else {
      stop("You are not supposed to change this column.")
    }

    replaceData(proxy, df, resetPaging = FALSE)  # important
  })

  observeEvent(reset(), {
    v$data <- data # your default data
  })

  output$mod_table <- DT::renderDataTable({
    DT::datatable(v$data, editable = TRUE)
  })
}

optimzationUI <- function(id) {
  ns <- NS(id)
  DT::dataTableOutput(ns("mod_table"))

}

shinyApp(
  ui = basicPage(
    mainPanel(
      numericInput("budget_input", label = h5("Total Budget"), value = 9000000),
      actionButton("opt_run", "Run"),
      actionButton("opt_reset", "Reset"),
      tags$hr(),
      optimzationUI("optimize")
    )
  ),
  server = function(input, output) {
    demodata<-input_data
    callModule(optimzation,"optimize", demodata,
               budget = reactive(input$budget_input),
               run = reactive(input$opt_run),
               reset = reactive(input$opt_reset))

  }
)

0 个答案:

没有答案