I have run various models (glm, rpart, earth etc) and exported the model object from each respective one into a folder on my computer. So I now have a folder with ~60 different models stored as seperate .rda files.
This was done by creating a model function and then applying it to a list of model types through the purrr map package (to avoid errors and termination).
I now want to load them back into r and compare them. Unfortunatley when I wrote my intial model script each model is stored as the same ie "Model.Object" (I didnt know how to do otherwise) so when I try to load each one individually into r it just overides each other. Each file is saved as glm.rda, rpart.rda, earth.rda etc but the model within is labelled Model.Object (for clarification).
So I guess I have a few questions; 1. It is possible to load in multiple .rda files into r into a list that can then be indexed 2. How to alter the model function that has been applied so that the 'model.object' name reads as the model type (e.g. glm, rpart etc)
Code:
Model.Function = function(Model.Type){
set.seed(0)
Model.Output = train(x = Pred.Vars.RVC.Data, y = RVC, trControl = Tcontrolparam,
preProcess = Preprocessing.Options, tuneLength = 1, metric = "RMSE",
method = Model.Type)
save(Model.Object, file = paste("./RVC Models/",Model.Type,".rda", sep = ""))
return(Model.Object)
}
Possibly.Model.Function = possibly(Model.Function, otherwise = "something wrong here")
result.possible = map(c("glm","rpart","earth"), Possibly.Model.Function)
For now, a rescue operation of your existing files might look something like this (following @nicola's comment about using the envir
argument to load()
):
rda2list <- function(file) {
e <- new.env()
load(file, envir = e)
as.list(e)
}
folder <- "./RVC Models"
files <- list.files(folder, pattern = ".rda$")
models <- Map(rda2list, file.path(folder, files))
names(models) <- tools::file_path_sans_ext(files)
Going forward, it would be easier to save your models as .Rds
files with saveRDS()
rather than using save()
. Then reassignment is easy upon loading the file. See e.g. this question and answer for more details on the matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With