saveRDS(object, file = "", ascii = FALSE, version = NULL, compress = TRUE, refhook = NULL)
readRDS(file, refhook = NULL)
NA, an ASCII representation is written; otherwise (default), a binary one is used. See the comments in the help for
NULLspecifies the current default version (2). Versions prior to 2 are not supported, so this will only be relevant when there are later versions.
"gzip"compression, or one of
"xz"to indicate the type of compression to be used. Ignored if
fileis a connection.
readRDS, an R object. For
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
".rds"file extension is most often used. Functions
unserializeprovide a slightly lower-level interface to serialization: objects serialized to a connection by
serializecan be read back by
readRDSand 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,
savewrites a single line header (typically
"RDXs\n") before the serialization of a single object (a pairlist of all the objects to be saved). Compression is handled by the connection opened when
fileis a file name, so is only possible when
fileis a connection if handled by the connection. So e.g.
urlconnections will need to be wrapped in a call to
gzcon. 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 non-ASCII saves.
load. The ‘R Internals’ manual for details of the format used.
## 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"))
Run the code above in your browser using DataCamp Workspace