JOSE DANIEL FERNANDEZ
JOSE DANIEL FERNANDEZ

Reputation: 191

R, Shiny, add values to a dataframe and save them

i have a code (copied of another post) that loads a dataframe and can add values to this data frame (with a input box), but this added values doesnt stay on the dataframe when i quit shiny. The question i have is how to save this added values to the original dataframe.

Code:

require(shiny)
setwd("C:/Users/DC7900/Documents/CENAGAS/Presupuesto/Pagos/")
iris<-read.csv("ConcentradoR.csv")

runApp(
  list(
    ui = fluidPage(
      headerPanel('Gasto'),
      sidebarPanel(
        textInput("mes", label="fecha", value="Ingresar fecha"),
        textInput("concepto", label="Concepto", value=""),
        numericInput("partida", label="Partida", value=""),
        numericInput("actividad", label="Actividad", value=""),
        numericInput("monto", label="Monto", value=""),
        actionButton("addButton", "UPLOAD!")
      ),
      mainPanel(
        tableOutput("table"))
    ),

    server = function(input, output) {     
      # just a small part of iris for display
      iris_sample <- iris[sample(nrow(iris), 10),]
      row.names(iris_sample) <- NULL

      # The important part of reactiveValues()
      values <- reactiveValues()
      values$df <- iris_sample
      addData <- observe({

        # your action button condition
        if(input$addButton > 0) {
          # create the new line to be added from your inputs
          newLine <- isolate(c(input$mes, input$concepto, input$partida, input$actividad, input$monto))
          # update your data
          # note the unlist of newLine, this prevents a bothersome warning message that the rbind will return regarding rownames because of using isolate.
          isolate(values$df <- rbind(as.matrix(values$df), unlist(newLine)))
        }
      })
      output$table <- renderTable({values$df}, include.rownames=F)
    }
  )
)

Thank you very much

Upvotes: 1

Views: 4194

Answers (1)

Jimbo
Jimbo

Reputation: 938

Adding the line below will create df called save_data that you can access in your local environment once you quit the shiny app.

  # your action button condition
    if(input$addButton > 0) {
      # create the new line to be added from your inputs
      newLine <- isolate(c(input$mes, input$concepto, input$partida, input$actividad, input$monto))
      # update your data
      # note the unlist of newLine, this prevents a bothersome warning message that the rbind will return regarding rownames because of using isolate.
      isolate(values$df <- rbind(as.matrix(values$df), unlist(newLine)))
      save_data <<- values$df
    }

You could also have(in place of that line) like

write.csv(values$df, file = "ConcentradoR.csv")

but also see write.table, you may need to specify some parameters to make sure it's formatted correctly

Upvotes: 2

Related Questions