I spent the weekend enjoying my leisure time while my computer assiduously ran a series of 31 bayesian models in R (using the brms package. I assigned each of these model objects a name. So when I returned this morning I had 31 model objects in my workspace. Sadly, what I did not do on Friday afternoon was write code to save each of these model objects. It will take a LONG time to rerun the models a fair bit of code to save each of them. So I was wondering if it was possible to save the model objects by passing their name through a for-loop. Simple example included below
# Two models
mod1 <- lm(Sepal.Length ~ Species, data = iris)
mod2 <- lm(Sepal.Width ~ Species, data = iris)
Now what I want to do for my example is grab the object names in the workspace as a list of names, stored as strings, via ls()
. However for the purposes of this simple example I will just store the two model object names as a list manually
objNames <- c("mod1", "mod2")
Now for the for-loop passing the names of the objects as strings into the save()
function…
for(i in 1:length(objNames)) {
save(objNames[i],
file = paste0(objNames[i], ".RData"))
}
….which obviously does not work because I don’t know anything about evaluation…and throws the error…
Error in save(objNames[i], file = paste0(objNames[i], ".RData")) :
object ‘objNames[i]’ not found
Any help much appreciated