Save all objects to disk as separate files
You can easily save one or more objects to disk using save() or save.image(). However, if you want to save many items, each as a separate file, you have to use a loop and a paste() command…
It is easy to save the objects you have stored in the R Console. You can save individual items with save().
save(..., list = character(), file = "filename")
You can either type the names of the items to save, separated by commas, or provide a list. The list can be any object or command that produces names of objects.
If you want to save all items, you have then you can use:
save(list = ls(), file = "filename")
A convenience function save.image() does the same thing. You just specify the filename to hold the data. If you omit the filename R saves to a default file: this is what is opened when R starts up and what happens when you say “yes” when asked if you want to save the workspace.
Both save() and save.image() will create a single file when you run them. In most cases this is helpful but there are times when you want to save objects as separate files. One such occasion might be when you are making an R package. You will need to save data items as separate .RData files and functions as .R files.
You can use a simple loop and the paste() function to save all objects to a folder as separate files.
obj <- ls() for(i in 1:length(obj)) { save(list = (obj[i]), file = paste(obj[I], ".RData", sep = "")) } rm(i, obj)
You start by listing everything and saving the result to a named object (obj in this case).
The loop runs for as many times as there are items in the listing; length(obj). Each time the loop goes around it takes the name of an item; list = obj[i] and saves it to a file.
The filename is built using the paste() command. This joins things together, with the sep =parameter telling R what character to use (if any) between items. In the example I used the name of the item; obj[i] and added .RData to the name. Note that “.RData” is in quotes. The sep = “” part tells R to use no character in the joining.
The result is that every item obtained by ls() is saved to disk as a separate .RData file. The files will go to your working directory unless you alter it, either using the setwd() command or by prepending a pathname to the paste() command.
Separate listing for functions and variables
If you have both data and functions in your workspace, you’ll need to split them. I found these custom functions on the [R] Help forum via a web search:
ls.funs <- function(env=sys.frame(-1)) unlist(lapply(ls(env=env), function(x) if(is.function(get(x)))x)) ls.vars <- function(env=sys.frame(-1)) unlist(lapply(ls(env=env), function(x) if(!is.function(get(x)))x)) # To use type: ls.funs() ls.vars()
You can use these new functions instead of ls() and make a new object containing the names. Simply use “.RData” for varaibles (data) and “.R” for functions to get the correct file extensions.
Comments are closed.