闪亮的 DT 通过 UI 上的编辑替换反应对象的值

问题描述 投票:0回答:0

我想执行预算优化,首先会根据用户对客户、国家/地区等的选择从数据库中获取预算。有一次,我进行了优化的第一阶段,用户可能希望执行不同的优化预算。在用户对表格进行编辑之前,我如何从数据库中获得初始预算,一旦用户进行编辑,这些预算(用户输入)应该是要优化的预算。在下面的代码中,我已经生成了几个月的虚拟数据,而月份是 ui 中的一个 selectInput。

library(DT)
library(shiny)
library(tidyverse)


months = c('jan', 'feb', 'mar')
for (this_month in months){
  budget = tibble(country = c('us', 'fr', 'de'),
                  budget = c(100 + sample.int(1e2, 1, replace = TRUE), 
                             200 + sample.int(1e2, 1, replace = TRUE), 
                             300 + sample.int(1e2, 1, replace = TRUE)))
  write_csv(budget, paste0(this_month, '.csv'))
}


ui <- fluidPage(
  selectInput('month', 'Select Month', c('jan', 'feb', 'mar'), 'mar'),
  DT::dataTableOutput('allocated'),
  actionButton("update", "update")
)

server <- function(input, output) {
  
 df  <- reactive({
    month = input$month
    read_csv(paste0(month, '.csv'))
  })
  
 rv = reactiveVal(df = df())
  observeEvent(input$update, {
    if (input$update <1) rv$df <- df() %>% mutate( mrA = budget * 0.25, mrB = budget * 0.75)
    else rv$df <- rv$df[,c(1:2)] %>% mutate( mrA = budget * 0.25, mrB = budget * 0.75)
    print(rv$df)
  }, ignoreNULL = FALSE)
  
  proxy <- dataTableProxy('allocated')
  
  observeEvent(input[["allocated_cell_edit"]], {
    info <- input[["allocated_cell_edit"]]
    str(info)
    print(info)
    i = info$row
    j = info$col
    v = info$value
    rv$df[i, j] <<- DT::coerceValue(v, rv$df[i, j])
    #rv$df1 <- editData(rv$df, info, proxy)
    print(rv$df)
  })
  
  output$allocated <- renderDT({
    datatable(
      rv$df,
      editable = list(target = "cell", disable = list(columns = c(1,3,4))),
      options = list(dom = 'frtBip')
    )
  })
  
}

shinyApp(ui = ui, server = server)
r shiny dt
© www.soinside.com 2019 - 2024. All rights reserved.