在R Shiny应用程序中编辑DT以更新第二个DT表

时间:2019-03-05 19:01:35

标签: r datatable shiny

我正在尝试使用闪亮的应用程序,如果用户编辑第一个表,它将修改第二个表的值。如果您看到代码,则在x1函数中有两个表x2tableMod。表x1中的值基于表x2和一些计算。因此,我想做的是,如果用户使用表x1中的edit修改值,则应该通过反向计算表x2中的值来更新值。下面是代码,除了如何进行编辑和反向计算:

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

df <- data.frame(Channel = c("A", "B","C"),
                 Current = c(2000, 3000, 4000),
                 Modified = c(2500, 3500,3000),
                 New_Membership = c(362, 577,575),
                 stringsAsFactors = FALSE)
rates <- data.frame(
                 low = c(1000, 2000, 3000),
                 high = c(4000, 6000,8000),
                 stringsAsFactors = FALSE)

#### Module 1 renders the first table
tableMod <- function(input, output, session, modelRun,modelData,ratesData,budget){


  observeEvent( input$x1_cell_edit, {
    cat ('input$x1_cell_edit \n')
    info = input$x1_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = info$value
    df[i, j] <- DT:::coerceValue(v, df[i, j])
    assign("df", df, envir = .GlobalEnv)

  })


  output$x1 <- DT::renderDataTable({
    modelRun()
   modelData <- df
   ratesData <- rates
    isolate(
      datatable(
        modelData %>% 
          mutate(Current = (ratesData$low * budget())) %>%
          mutate(Modified = (ratesData$high * budget())),
         #mutate(New_Membership  = round((Current*ratesData$low + Modified*ratesData$high)*budget(),0) ),
        selection = 'none', editable = TRUE
      )
    )
  })
  output$x2<- DT::renderDataTable({
    ratesData
  })


}
firstTableUI <- function(id) {
  ns <- NS(id)
  dataTableOutput(ns("x1"))
}
secondTableUI <- function(id) {
  ns <- NS(id)
  dataTableOutput(ns("x2"))
}

ui <- function(request) {
  fluidPage(
    firstTableUI("opfun"),
    numericInput("budget_input", "Total Forecast", value = 2),
    actionButton("opt_run", "Run"),
    secondTableUI("opfun")
  )
}
server <- function(input, output, session) {

  callModule( tableMod,"opfun",
              modelRun = reactive(input$opt_run),
              modelData = df,
              ratesData = rates,
              budget = reactive(input$budget_input))

  observeEvent(input$opt_run, {
    cat('HJE')
  })
}

shinyApp(ui, server, enableBookmarking = "url")

0 个答案:

没有答案