R: save all data.frames in workspace to split .RData files

I have several data.frames

in the environment that I would like to keep in separate .RData files. Is there a feature that can save your entire workspace?

I usually do this with the following function:

save(x, file = "xy.RData")

      

but is there a way that i could keep all data.frames seperate at once?

+3


source to share


3 answers


Creation of a bunch of different files is not the same as save()

vectorized. It's probably better to use a loop here. First, get a vector of all your data.frame names.

dfs<-Filter(function(x) is.data.frame(get(x)) , ls())

      

Now write each file.



for(d in dfs) {
    save(list=d, file=paste0(d, ".RData"))
}

      

Or if you just wanted them all in one file

save(list=dfs, file="alldfs.RData")

      

+8


source


To save your workspace, you just need to do:

save.image("willcontainworkspace.RData")

      



This creates a single file that contains the entire workspace, which may or may not be what you want, but your question was not completely clear to me.

+1


source


Similar to @MrFlick's approach, you can do something like this:

invisible({
  sapply(ls(envir = .GlobalEnv), function(x) {
    obj <- get(x, envir = .GlobalEnv)
    if (class(obj) == "data.frame") {
      save(obj, file = paste0(x, ".RData"))
    }
  })
})

      

0


source







All Articles