Functions to write a single R object to a file, and to restore it.
1 2 3 4
R object to serialize.
a connection or the name of the file where the R object is saved to or read from.
a logical. If
the workspace format version to use.
a logical specifying whether saving to a named file is
a hook function for handling reference objects.
These functions provide the means to save a single R object to a
connection (typically a file) and to restore the object, quite
possibly under a different name. This differs from
load, which save and restore one or more named
objects into an environment. They are widely used by R itself, for
example to store metadata for a package and to store the
help.search databases: the
".rds" file extension
is most often used.
provide a slightly lower-level interface to serialization: objects
serialized to a connection by
serialize can be read back by
readRDS and conversely.
All of these interfaces use the same serialization format, which has
been used since R 1.4.0 (but extended from time to time as new
object types have been added to R). However,
save writes a
single line header (typically
"RDXs\n") before the
serialization of a single object (a pairlist of all the objects to be
Compression is handled by the connection opened when
file is a
file name, so is only possible when
file is a connection if
handled by the connection. So e.g.
connections will need to be wrapped in a call to
If a connection is supplied it will be opened (in binary mode) for the
duration of the function if not already open: if it is already open it
must be in binary mode for
saveRDS(ascii = FALSE) or to read
readRDS, an R object.
The ‘R Internals’ manual for details of the format used.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
## save a single object to file saveRDS(women, "women.rds") ## restore it under a different name women2 <- readRDS("women.rds") identical(women, women2) ## or examine the object via a connection, which will be opened as needed. con <- gzfile("women.rds") readRDS(con) close(con) ## Less convenient ways to restore the object ## which demonstrate compatibility with unserialize() con <- gzfile("women.rds", "rb") identical(unserialize(con), women) close(con) con <- gzfile("women.rds", "rb") wm <- readBin(con, "raw", n = 1e4) # size is a guess close(con) identical(unserialize(wm), women) ## Format compatibility with serialize(): con <- file("women2", "w") serialize(women, con) # ASCII, uncompressed close(con) identical(women, readRDS("women2")) con <- bzfile("women3", "w") serialize(women, con) # binary, bzip2-compressed close(con) identical(women, readRDS("women2"))
Want to suggest features or report bugs for rdrr.io? Use the GitHub issue tracker.