向现有数据框添加值并在 Shiny 中本地保存

Adding values to existing dataframe and save locally in Shiny

我创建了以下 Shiny App。它采用两个值,将它们添加到 table 中,当点击“保存”按钮时,它会将 table 本地保存在 csv 文件中。接下来我想做的(我无法全神贯注)是,每次我打开应用程序时检查文件值是否已经存在,如果 TRUE 打开该文件并从那里开始添加:

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)

# Define UI for application that draws a histogram
ui=pageWithSidebar(headerPanel("Adding entries to table"),
                   sidebarPanel(textInput("text1", "Column 1"),
                                textInput("text2", "Column 2"),
                                actionButton("update", "Update Table"),
                                actionButton("save", "Save")
                                )                   ,
                   mainPanel(tableOutput("table1")))

# Define server logic required to draw a histogram
server=function(input, output, session) {
    values <- reactiveValues()
    values$df <- data.frame(Column1 = NA, Column2 = NA)
    newEntry <- observe({
        if(input$update > 0) {
            newLine <- isolate(c(input$text1, input$text2))
            isolate(values$df <- rbind(values$df, newLine))
            }
        })
    Save <- observe({
        if(input$save > 0){
            write.csv(values$df, "responses/values.csv", row.names = FALSE)
        }
    })
    output$table1 <- renderTable({values$df})
}#Server End


# Run the application 
shinyApp(ui = ui, server = server)

您可以使用 file.exists 检查文件是否已创建并将新值附加到现有数据。

library(shiny)

ui=pageWithSidebar(headerPanel("Adding entries to table"),
                   sidebarPanel(textInput("text1", "Column 1"),
                                textInput("text2", "Column 2"),
                                actionButton("update", "Update Table"),
                                actionButton("save", "Save")
                   )                   ,
                   mainPanel(tableOutput("table1")))

# Define server logic required to draw a histogram
server=function(input, output, session) {
  values <- reactiveValues()
  if(file.exists('responses/values.csv')) values$df <- read.csv('responses/values.csv')
  else values$df <- data.frame(Column1 = NULL, Column2 = NULL)
  newEntry <- observe({
    if(input$update > 0) {
      newLine <- isolate(data.frame(Column1 = input$text1, Column2 = input$text2))
      isolate(values$df <- rbind(values$df, newLine))
    }
  })
  Save <- observe({
    if(input$save > 0){
      write.csv(values$df, "responses/values.csv", row.names = FALSE)
    }
  })
  output$table1 <- renderTable({values$df})
}#Server End


# Run the application 
shinyApp(ui = ui, server = server)