R: Save all data.frames in workspace to separate .RData files

﹥>﹥吖頭↗ 提交于 2021-02-04 16:11:05

问题


I have several data.frames in an environment which I would like to save into separate .RData files. Is there a function which is able to save to whole workspace?

I usually just do this with the following function:

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

but is there a way I could save all the data.frames separately at once?


回答1:


Creating a bunch of different files isn't how save() is vectorized. Probably better to use a loop here. First, get a vector of all of your data.frame names.

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

Now write each to a 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")



回答2:


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 wasn't completely clear to me.




回答3:


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"))
    }
  })
})


来源:https://stackoverflow.com/questions/31296398/r-save-all-data-frames-in-workspace-to-separate-rdata-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!