在R Shiny中本地保存从一个会话到下一个会话的反应数据帧的简单方式



如何在本地保存在R会话期间修改的反应性数据帧,以便在下一个R会话中使用?下一个R会话是否涉及重新启动R、注销/登录计算机等,而不提示用户下载并保存.csv或其他文件;我认为最好的方法是将数据帧保存到用户计算机上的某种类型的临时或存档文件夹中,但我不知道如何设置它。用户简单地点击";保存";操作按钮(下面MWE代码中的占位符(,保存的数据帧将可用于下一个会话。如果用户没有点击";保存";,则在重新启动会话时检索最后保存的数据帧,或者如果没有存档的数据帧则会话简单地按照下面的MWE代码以默认数据帧data.frame(x = c(1, 2, 3))开始。

并非所有会话和所有连接的数据都相同:如果一个用户更新数据,它只会影响用户看到的数据,而不会影响其他用户。

通过研究,我知道有很多选择,但我正在为像我这样的相对新人寻找简单的开始。如果可行的话,储蓄可以在以后变得更加复杂。

我将添加一个";重置";按钮,以便用户可以在data.frame(x = c(1, 2, 3)的示例中恢复到原始数据帧(。

MWE代码:

library(rhandsontable)
library(shiny)
myDF <- data.frame(x = c(1, 2, 3))
ui <- fluidPage(
br(),
fluidRow(
column(6,
actionButton('addCol','Add'),
actionButton('savTbl','Save')
)
),
br(),
rHandsontableOutput('hottable')
)
server <- function(input, output, session) {
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)

以下是ismirsehregal在帖子中的慷慨解决方案如何在使用rhandontable R包生成的表时实现shinyStore?:

代码:

# If not installed already, un-comment and run the below 3 lines to install shinyStore package:
# 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', 'Add column'),
actionButton("save", "Save", icon("save")),
actionButton("clear", "Clear", icon("stop")) # add
)),
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, {
# clear tracking table:
uiTable(myDF)

# clear shinyStore:
updateStore(session, name = "uiTable", myDF)
}, ignoreInit = TRUE)

observeEvent(input$store$uiTable, {
uiTable(as.data.frame(input$store$uiTable))
})
}
shinyApp(ui, server)

相关内容

最新更新