|
|
|
More R Saving Objects
This page has the following sections:
Saving
Removing
Using saved files
Writing
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.
Saving
The command:
> 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 list:
> 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.
Removing
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 file argument.
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"))
Using saved files
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:
> attach("xyz.rda")
Alternatively, you can throw the objects into the global environment:
> load("xyz.rda")
Keeping objects separate is often the cleaner solution.
Writing
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
Some hints for the R beginner
First Version: 2010 March 07
Last Modified: 2010 May 09
Direct access to this page is via
http://www.burns-stat.com/pages/Tutor/more_R_savingobjects.html
|
|
|
|
|
|