我的计算集群最近更新为R版本R 3.6.0,并删除了旧版本的R。我一直在R 3.4.0中运行我的项目。我认为这很好,运行了一些代码,并在我的R 3.6.0会话中将输出保存为:
saveRDS(output, output.path)
Run Code Online (Sandbox Code Playgroud)
然后将此文件传输到另一台计算机上,在该计算机上进行交互式R使用。这台计算机正在运行R/3.4.0,并且不能选择更新R的版本。当我打开上面的文件时,出现以下错误:
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
Run Code Online (Sandbox Code Playgroud)
真是可惜 我不是这两台计算机上的系统管理员,因此我不能仅同步版本。这是我的问题:
有没有一种方法可以saveRDS()在R 3.6.0中使用写入文件,从而使其在R 3.4.0环境中向后兼容?
据我了解,从这里你必须设置version = 2在saveRDS:
序列化格式版本3成为序列化和保存工作区的默认格式(save(),serialize(),saveRDS(),compiler :: cmpfile())。版本3.5.0之前的R版本无法读取格式3的序列化数据。序列化格式版本2仍受支持,可以在保存/序列化功能中通过版本= 2选择。通过将环境变量R_DEFAULT_SAVE_VERSION和R_DEFAULT_SERIALIZE_VERSION设置为2,可以将整个R会话的默认值更改回2。为了实现最大的后向兼容性,R CMD构建生成的文件'vignette.rds'和'partial.rdb'的序列化格式为版本2 ,并且默认情况下重新保存会产生序列化格式版本2的文件(除非原始文件已经是格式版本3)。
通过演示扩展我的评论:
$ 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
$
Run Code Online (Sandbox Code Playgroud)
我使用正常的R版本,显示为3.6.0,然后通过Rocker启动R 3.4.0,并显示了其版本。
正如预期的那样,它首先会失败-并且一旦恢复了数据,它就会按预期version=2工作。