save R objects in the background using R Shiny

Viewed 415

i want to save R-object using R-Shiny-App. The with the normal Download Button you can save files, but have to define a directory every time. I want to save R-Objects without asking for the directory.

i tried the naive way using a reactive Button, doesnt work

For example to save this vector inside of a reactive value...

library(shiny)

vec <- c(1,2,3,4)

ui <- fluidPage(
  actionButton("saveData", "Save")
)

server <- function(input,output,session) {


  vec <- reactive({
    vec <- c(1,2,3,4)
    vec
  })

  observeEvent(input$saveData,{
    save(vec(), file = 'vec.RData')
  })

}
shinyApp(server = server, ui = ui)



same problem while trying to create and delete folders. I tink the problem is the function eventReactive() because it tries to give out a object, but cant. is there any other function i could use?

1 Answers

Indeed, that does not work with eventReactive. Use observeEvent instead. Moreover, in the save function, we provide the objects to be saved, but by their names. If you do save(vec(), file = "vec.RData"), then the save function will search for an object named vec(). So you should do something like:

  observeEvent(input$saveData,{
    x <- vec()
    save(x, file = 'vec.RData')
  })

I would recommend saveRDS to save a single R object.

Related