Convert raw vector to R object

Viewed 1213

How do you convert a raw vector back to an R object without writing to disk? I want to read a stream of base64 data and convert it to its R object representation. Here is an example - how would I get back the lm object from the raw vector?

## some rdata -- writes to temp file!
mod <- lm(mpg ~ cyl, data=mtcars)
f1 <- tempfile()
save(mod, file=f1, compress="bzip2")

library(base64enc)
r1 <- readBin(f1, "raw", n=file.info(f1)[1, "size"])
r2 <- base64decode(base64encode(file(f1, "rb")))  # emulate input base64
identical(r1, r2)

## I can get mod back by writing to file and loading, but how to just
## load from a raw vector?
rm(mod)  # get rid of mod
f2 <- tempfile()
writeBin(r2, f2)
load(f2)  # mod is back
2 Answers
Related