I'm trying to create a shiny app that allows me to fit linear models, display informations about them, and then save them.
I'm facing an issue : when I save a model, it takes a huge place. Here is a simplified code :
library(shiny)
library(ggplot2)
ui <- shinyUI(fluidPage(
titlePanel("Save linear Model"),
sidebarLayout(
sidebarPanel(
actionButton("save","SAVE !")
),
mainPanel(
textOutput("saved")
)
)
))
server <- shinyServer(function(input, output) {
load("donnees/new/V283/V283_complete.RData")
observeEvent(input$save,{
lm.fit<-lm(price~.,data=diamonds)
save(lm.fit, file="question-x-validated/my-model.RData")
output$saved<-renderText("Saved")
})
})
shinyApp(ui = ui, server = server)
In fact, the more objects I create/load in my app, the bigger my saved model is. For exemple, the object I load with :
load("donnees/new/V283/V283_complete.RData")
is 275.1MB. If I save my lm.fit after loading it, my rdata file is 36.9Mb. If I save my lm.fit without loading it, my file is 13Mb. If I save my lm.fit directly from R (without using my shiny app), the file is 6,57Mb
As suggested in this link, it might be an environment issue. But it seems to me that the fact I'm using shiny is adding some difficulties, as none of the technique suggested by the above link worked in my case.
I also tried using the saveRDS function. And also replaced :
lm.fit<-lm(price~.,data=diamonds)
by
assign("lm.fit",lm(price~.,data=diamonds),envir=globalenv())
It changes the file size, but It never gets as little as 6.57Mb.
As in my real code, I import really big data sets, my real models gets really huge (more than 500Mb), and It makes my Shiny App really slow when it loads/saves these models.
I would really appreciate any help you can provide.
EDIT :
It seems my issue comes from the "terms" element of my model, as if I do :
lm.fit<-lm.fit[1:11]
prior to saving my model, my file is 5.92Mb ! But as you know, the "terms" element is needed to use predict(). And only doing :
attr(lm.fit$terms,".Environment") = c()
does not work.
Also, funny thing :
lm.fit$terms<-NULL
and lm.fit<-lm.fit[-12]
does not change anything while lm.fit<-lm.fit[1:11]
does.