使用 R 闪亮包保存数据(在数据表中)



我正在制作一个R闪亮的应用程序(我对R shiny很陌生),它获取数据作为输入并将数据投影为表格(使用DT包)。但是,当插入新数据并提交时,不会添加新行,而是添加以前的观察结果(以前提交的数据只是更新。因此,我该怎么做才能保存新的数据数据?

代码中的主要问题是您创建了一个新的数据框并将其替换为前一个数据框。我稍微修改了您的服务器代码。我添加了一个全局变量TabData,用于将数据表中保存以前的数据,并将其与要添加到表中的新数据rbind。请参阅下面的修改代码:

library(shiny)
library(car)    # Import library to use recode() function
shinyServer(function(input, output) {
  #Global variable to save the previous data in the data table
  TabData <- data.frame()
  values <- reactiveValues()
  # Calculate damage and loss (just ab experiment)
  observe({
    input$action_Calc
    values$int <- isolate({input$reduction * 10})
    values$amt <- isolate({input$lost}) + values$int
    values$com<-isolate({input$community})
    values$disaster <- isolate({input$disaster})
    values$name <- isolate({input$name})
  })
  # Display values entered
  output$text_principal <- renderText({
    input$action_Calc
    paste("reduction: ", isolate(input$reduction))
  })
  output$text_intrate <- renderText({
    input$action_Calc
    paste("Vegetation: ", isolate(input$veg))
  })
  output$text_int <- renderText({
    if(input$action_Calc == 0) ""
    else
      paste("Damage:", values$int)
  })
  output$text_amt <- renderText({
    if(input$action_Calc == 0) ""
    else 
      paste("Loss:", values$amt)
  })
  Data <- reactive({
    browser()
    if (input$action_Calc > 0) {
      df <- data.frame(
        Community= values$com,
        Disaster = values$disaster,
        Name = values$name,
        Damage=values$amt,
        Loss=values$int

      )
      return(list(df=df))
    }
  })

  output$responses <- DT::renderDataTable(DT::datatable({
    if (is.null(Data())) {return()}
    #Row bind the new data to be added to the table
    TabData <<- rbind(TabData, Data()$df)
    datum<-TabData
    datum

  }))
}) 

希望对您有所帮助!

最新更新