如何在 Shiny 应用程序中编辑后保留数据表的过滤(或不同页面)视图?

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

我正在写一个闪亮的应用程序,我正在渲染一个可编辑的数据表。在某些情况下,我希望用户过滤表格或转到不同的页面,然后对表格进行编辑。进行此编辑后,我希望在显示表中的编辑时保留表的当前视图。对一列的编辑也会更改另一列中的值,因此这两个编辑都需要在保留视图的同时显示。

这是我到目前为止想出的代码

library(shiny)
library(DT)

# create a sample data frame with 50 entries
df <- data.frame(
  name = paste0("Person ", 1:50),
  age = sample(20:60, 50, replace = TRUE),
  salary = sample(2000:5000, 50, replace = TRUE),
  stringsAsFactors = FALSE
)

# create a shiny app
ui <- fluidPage(
  DTOutput("table")
)

server <- function(input, output, session) {
  # create a reactiveValues object to store the data frame
  rv <- reactiveValues()
  rv$df <- df
  
  # render the table
  output$table <- renderDT({
    datatable(
      rv$df,
      rownames = F,
      editable = T,
      filter = "top",
      selection = "none",
      extensions = c(
        "ColReorder",
        "Buttons"
      ),
      options = list(
        dom = "lBRrftpi",
        autoWidth = F,
        pageLength = 20,
        scrollX = F,
        ColReorder = T,
        buttons = list(list(extend = 'csv', filename= 'data'), 'print', 'copy')
      )
    )
  })
  
  # update the table when edited
  observeEvent(input$table_cell_edit, {
    info <- input$table_cell_edit
    i <- info$row
    j <- info$col
    v <- info$value
    
    new_i <- i
    new_j <- j + 1
    new_val <- v * 100
    new_info <- data.frame(
      row = new_i,
      col = new_j,
      value = new_val
    )
    
    rv$df <<- editData(rv$df, info, rownames = F)
    
    if(j == 1){
      rv$df <<- editData(rv$df, new_info, rownames = F)
    }
    
    replaceData(proxy = dataTableProxy("table"), data = rv$df, resetPaging = FALSE)
  })
  
}

# run the app
shinyApp(ui, server)

虽然表格中的编辑和另一列中的相关更改确实有效,但表格视图会在我编辑单元格后立即重置。有人可以帮我编写编辑后保留视图的代码吗?

r shiny dt
© www.soinside.com 2019 - 2024. All rights reserved.