如何跨R会话保存rhandsontable生成的响应式数据框?
问题与解决方案:rhandsontable跨会话保存用户输入
问题描述
我尝试用shinyStorePlus包实现跨R会话保存用户输入,但在使用rhandsontable渲染的响应式数据框场景下无法生效。用户可通过rhandsontable点击添加列,还能像Excel一样手动编辑列数据。需要明确:
shinyStorePlus是否支持这类复杂输入机制,实现表格/数据框的跨会话保存?- 有没有不依赖
shinyStorePlus的更佳解决方案?(注:必须使用rhandsontable)
核心需求:保存用户对表格的全部输入操作以实现跨R会话复用,后续需添加按钮将数据框重置为默认设置。
原测试代码(shinyStorePlus版本)
library(rhandsontable) library(shiny) library(shinyStorePlus) myDF <- data.frame(x = c(1, 2, 3)) ui <- fluidPage( initStore(), # 启用shinyStorePlus br(),fluidRow(column(6,actionButton('addCol','Add'))),br(), rHandsontableOutput('hottable') ) server <- function(input, output, session) { ### 配置shinyStorePlus实现跨会话保存 appid <- "application002" setupStorage( appId = appid, inputs = TRUE ) #### EmptyTbl <- reactiveVal(myDF) observeEvent(input$hottable, { EmptyTbl(hot_to_r(input$hottable)) }) output$hottable <- renderRHandsontable({ rhandsontable(EmptyTbl(),useTypes = FALSE) }) observeEvent(input$addCol, { newCol <- data.frame(c(1, 2, 3)) names(newCol) <- paste("Col", ncol(hot_to_r(input$hottable)) + 1) EmptyTbl(cbind(EmptyTbl(), newCol)) }) } shinyApp(ui, server)
可行解决方案(shinyStore版本)
替换为shinyStore包可实现需求,该方案支持手动保存表格状态、重置表格至默认值,且能跨会话恢复数据:
安装shinyStore
若未安装,先执行以下代码:
# install.packages("devtools") # library(devtools) # install_github("trestletech/shinyStore")
完整代码
library(rhandsontable) library(shiny) library(shinyStore) myDF <- data.frame(x = c(1, 2, 3)) ui <- fluidPage( initStore("store", "shinyStore-ex1"), br(), fluidRow(column( 6, actionButton('addCol', '添加列'), actionButton("save", "保存", icon("save")), actionButton("clear", "重置", icon("stop")) # 重置按钮 )), br(), rHandsontableOutput('hottable') ) server <- function(input, output, session) { uiTable <- reactiveVal(myDF) output$hottable <- renderRHandsontable({ rhandsontable(uiTable(), useTypes = FALSE) }) observeEvent(input$hottable, { uiTable(hot_to_r(input$hottable)) }) observeEvent(input$addCol, { newCol <- data.frame(c(1, 2, 3)) names(newCol) <- paste("Col", ncol(hot_to_r(input$hottable)) + 1) uiTable(cbind(uiTable(), newCol)) }) observeEvent(input$save, { updateStore(session, name = "uiTable", uiTable()) }, ignoreInit = TRUE) observeEvent(input$clear, { # 重置响应式表格 uiTable(myDF) # 重置存储中的数据 updateStore(session, name = "uiTable", myDF) }, ignoreInit = TRUE) observeEvent(input$store$uiTable, { uiTable(as.data.frame(input$store$uiTable)) }) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Curious Jorge - user9788072
相关产品推荐
相关产品推荐

