More R Saving Objects
This page has the following sections:
Remember that any files that you create with commands on this page will be put into R’s working directory. See More R Startup to see what the working directory is, and how to change it.
> save(x, file="x.rda")
is a very simple use of the function. Often you want to save more than one object into the file. There are two styles of doing this. In analogy of what we’ve already done, you can do:
> save(x, y, z, file="xyz.rda")
Alternatively, you can provide a vector of character strings naming the objects you want to keep. The name of the argument to use in this case is (perhaps confusingly) called
> save(list=c("x", "y", "z"), file="xyz.rda")
So why are there two different ways of doing the same thing? If you are saving just one or two objects, then the first form is easier (fewer keystrokes). If you are saving a large number of objects, then the second form is often easier. (The second form can be done inside a function.)
You can remove objects from your global environment. Do this with the
rm function. You give arguments to this function just like the
save function, except you don’t give it a
You can remove three objects with a command like:
> rm(x, y, z)
or you can do the exact same thing with the command:
> rm(list=c("x", "y", "z"))
In a new session when you want to use objects that have previously been saved, you have a choice of how to treat them.
You can keep them in a separate location on the search list:
Alternatively, you can throw the objects into the global environment:
Keeping objects separate is often the cleaner solution.
When you are writing out data, you have control over the character that separates data.
If you want to write a tab-separated file, do:
> write.table(x, "x.txt", sep="\t")
If you want to write a comma-separated file, do:
> write.table(x, "x.csv", sep=",")
In either case
x should be a matrix or a data frame.
Back to top level of Impatient R