简体   繁体   中英

how to save changes before adding new column R shiny reactive datatable

after editing existing cells, how do i make the cell values stay edited and not reset to original when i add a new column? tried using reactiveValues without success. below is the reproducible code,.

runApp(list(
  ui=pageWithSidebar(headerPanel("Adding entries to table"),
                     sidebarPanel(actionButton("update", "Add Column")),
                     mainPanel(DT::dataTableOutput("data"))),
  
  server=function(input, output, session) {
    df <- data.frame(Channel = c("A", "B","C"),
                     Current = c(2000, 3000, 4000),
                     Modified = c(2500, 3500,3000),
                     stringsAsFactors = FALSE)
    
    
    #smth <- reactiveValues(df2=integer(NROW(df)))
    values <- reactiveValues(df=df)
    proxyTable <<- DT::dataTableProxy("data")
    
    observeEvent(input$data_cell_edit, {
      info = input$data_cell_edit
      row = info$row
      col = info$col 
      value = info$value
      values$df[[row,col]] = value
      replaceData(proxyTable, values$df) 
    })
    
    newEntry <- observe({
      
      if(input$update > 0) {
        isolate({
          values$df[,paste0('NewCol', ncol(values$df) + 1)] <- integer(NROW(df))
        })
      }
    })
    output$data <- DT::renderDataTable(DT::datatable({values$df}, extensions = "AutoFill", editable = 'cell',
                                                     options = list(autoFill=list(focus="click"))),server=FALSE)
  }))

Like I said you need to update the data whenever is edited, that's what this code does.

library(shiny)
library(DT)

runApp(list(
  ui=pageWithSidebar(headerPanel("Adding entries to table"),
                     sidebarPanel(actionButton("update", "Add Column")),
                     mainPanel(DT::dataTableOutput("data"))),

  server=function(input, output, session) {
    df <- data.frame(Channel = c("A", "B","C"),
                     Current = c(2000, 3000, 4000),
                     Modified = c(2500, 3500,3000),
                     stringsAsFactors = FALSE)
    
    
    smth <- reactiveValues(df2=integer(NROW(df)))
    values <- reactiveValues(df=df)
    proxyTable <<- dataTableProxy("data")

    observeEvent(input$data_cell_edit, {
      info = input$data_cell_edit
    row = info$row
    col = info$col 
    value = info$value
    values$df[[row,col]] = value
      replaceData(proxyTable, values$df) 
    })

    newEntry <- observe({
     
      if(input$update > 0) {
        isolate({
        values$df[,paste0('NewCol', ncol(values$df) + 1)] <- smth$df2
        })
      }
    })
    output$data <- DT::renderDataTable(DT::datatable({values$df}, editable = 'cell'))
  }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM