Alicaceae
Alicaceae

Reputation: 93

Downloading .RData files with Shiny

I'm creating a Shiny app and one of my outputs is best saved as a .RData file for the user.

I can download data in various other formats but I'm not sure how to work with .RData. An alternate method to save R objects would be fine here too. Some dummy code on the server side would look like:

# Make widget
widget <- 1:42

# Download widget
output$widget <- downloadHandler(
  filename=paste0("widget_", Sys.Date(), ".RData"), 
  content=function(file){
    save(widget), file=file)
  }
)

I can click the download button fine and it refreshes my window but no items are put in the download queue.

Upvotes: 3

Views: 3316

Answers (2)

amir61
amir61

Reputation: 31

The easiest way to use downloadHandler for saving multiple objects is to combine them in a list and save in an RDS file.

output$save_btn <- downloadHandler(
    filename = "my_data.rds",
    content = function(file) {
      saved_data <- list("DATA1" = data1(), 
                             "DATA2" = data2, "DATA3" = data3)
      saveRDS(saved_data, file = file)
    }

Upvotes: 0

Praneeth Jagarapu
Praneeth Jagarapu

Reputation: 604

I tried to save a random Forest Model in .RData format. Below code worked for me. Hope the same will work for you.

ui.R

downloadButton('downloadModel', 'Download RF Model', class="dlButton")

server.R

Step1. Create a reactiveValue to save the reactive function, in my case the random forest model rf1()

# Create a reactive value rf2 to store the random forest model rf1().
rf2 <- reactiveValues()
observe({
  if(!is.null(rf1()))
  isolate(
    rf2 <<- rf1()
  )
})

Step2. Save the reactiveValue in the downloadHandler as you have done.

# Download Random Forest Model
  output$downloadModel <- downloadHandler(
    filename <- function(){
      paste("RF Model.RData")
    },

    content = function(file) {
      save(rf2, file = file)
    }
  )

Hope this works for you.

Upvotes: 4

Related Questions