Write a file using `saveRDS()` so that it is backwards compatible with old versions of R

Viewed 2863

My compute cluster recently updated to R version R 3.6.0 and deleted the old versions of R. I had been running my project in R 3.4.0. I decided this would be fine, ran some code, and saved the output during my R 3.6.0 session as:

saveRDS(output, output.path)

This file was then transferred to a different computer where interactive R use takes place. This computer runs R/3.4.0, and updating the version of R is not an option. When I go to open the above file, I get the following error:

readRDS(output.path)
Error in readRDS(output.path) : cannot read workspace version 3 written by R 3.6.0; need R 3.5.0 or newer

This is a bummer. I am not the system administrator on either of these computers, so I can't just synchronize the versions. This is my question:

Is there a way to write a file using saveRDS() in R 3.6.0 such that it would be backward compatible in an R 3.4.0 environment?

2 Answers

Expanding on my comment with a demo:

$ Rscript --version | head -1
R scripting front-end version 3.6.0 (2019-04-26)
$ Rscript -e 'saveRDS(1:10, file="foo.rds")'
$
$ docker run --rm -ti r-base:3.4.0 Rscript --version | head -1
R scripting front-end version 3.4.0 (2017-04-21)
$ docker run --rm -ti -v ${PWD}:/work -w /work r-base:3.4.0 Rscript -e 'print(readRDS("foo.rds"))'
Error in readRDS("foo.rds") :
  cannot read workspace version 3 written by R 3.6.0; need R 3.5.0 or newer
Calls: print -> readRDS
Execution halted
$
$ Rscript -e 'saveRDS(1:10, file="foo.rds", version=2)'
$ docker run --rm -ti -v ${PWD}:/work -w /work r-base:3.4.0 Rscript -e 'print(readRDS("foo.rds"))'
 [1]  1  2  3  4  5  6  7  8  9 10
$

I use my normal R version which I show to be 3.6.0, and I then launch R 3.4.0 via Rocker, also showing its version.

As expected, it first fails -- and once the data is resaved with version=2 it works as is should.

As I understand from here you have to set version = 2 in saveRDS:

Serialization format version 3 becomes the default for serialization and saving of the workspace (save(), serialize(), saveRDS(), compiler::cmpfile()). Serialized data in format 3 cannot be read by versions of R prior to version 3.5.0. Serialization format version 2 is still supported and can be selected by version = 2 in the save/serialization functions. The default can be changed back for the whole R session by setting environment variables R_DEFAULT_SAVE_VERSION and R_DEFAULT_SERIALIZE_VERSION to 2. For maximal back-compatibility, files ‘vignette.rds’ and ‘partial.rdb’ generated by R CMD build are in serialization format version 2, and resave by default produces files in serialization format version 2 (unless the original is already in format version 3).

Related