Reputation: 27
Background: Shiny application where users can train ML models and save model objects as a .rds file using saveRDS() in the temp directory. They then can look thru saved models and read them back using readRDS() to make predictions.
Problem: readRDS() won't open the file, saying no file exists and it can't open the connection.
Warning in gzfile(file, "rb") :
cannot open compressed file '/var/folders/hm/c8hhxwgn2vj0h4qsftqkr_8r0000gn/T//RtmpNpcs7g/Random Forrest18a9141b50ac5.rds', probable reason 'No such file or directory'
Warning: Error in gzfile: cannot open the connection
Code for saving RDS file:
my_file_name = reactive({
tempfile(pattern = paste0(input$method, x()), fileext = ".rds") # x() is increment counter
}) %>% bindEvent(input$save_mod)
reactive({
saveRDS(object = my_model(), file = my_file_name())
}) %>% bindEvent(input$save_mod)
observeEvent(input$save_mod,{
req(my_file_name())
t = rbind(storage(), list(paste0(input$method, x()), my_file_name()) )
storage(t) # stores model name + file path to dataframe for later use
})
Code for reading RDS file
output$test = renderPrint({
req(input$pick_mod)
readRDS(storage()[which(storage()[,1]==input$pick_mod), 2])
# which storage == mod returns the stored file path from the storage table created earlier
})
Upvotes: 0
Views: 161
Reputation: 53
It's a bit hard to diagnose without an example that can be run, but I think the issue is that you are running saveRDS within a reactive expression, when it should be in an observe or observeEvent.
I'd recommend putting everything to do with saving the file within the one observeEvent like this:
observeEvent(input$save_mod,{
my_file_name <- tempfile(pattern = paste0(input$method, x()), fileext = ".rds")
saveRDS(object = my_model(), file = my_file_name)
t = rbind(storage(), list(paste0(input$method, x()), my_file_name) )
storage(t) # stores model name + file path to dataframe for later use
})
observe and observeEvent are usually used for side-effects (like saving a file), whereas reactive and eventReactive are usually used for assigning values to variables. In your current code, you don't assign the reactive expression to anything. Reactive expressions are "lazy" meaning they are not evaluated until they are called. But you don't assign it and therefore never call it.
Upvotes: 1