Saving several variables in a single RDS file

点点圈 提交于 2020-06-17 00:51:26

问题


I want to pass a list of variables to saveRDS() to save their values, but instead it saves their names:

variables <- c("A", "B", "C")
saveRDS(variables, "file.R")

it saves the single vector "variables".

I also tried:

save(variables, "file.RData")

with no success


回答1:


You need to use the list argument of the save function. EG:

var1 = "foo"
var2 = 2
var3 = list(a="abc", z="xyz")
ls()
save(list=c("var1", "var2", "var3"), file="myvariables.RData")
rm(list=ls())
ls()

load("myvariables.RData")
ls()

Please note that the saveRDS function creates a .RDS file, which is used to save a single R object. The save function creates a .RData file (same thing as .RDA file). .RData files are used to store an entire R workspace, or whichever names in an R workspace are passed to the list argument.

YiHui has a nice blogpost on this topic.

If you have several data tables and need them all saved in a single R object, then you can go the saveRDS route. As an example:

datalist = list(mtcars = mtcars, pressure=pressure)
saveRDS(datalist, "twodatasets.RDS")
rm(list=ls())

datalist = readRDS("twodatasets.RDS")
datalist


来源:https://stackoverflow.com/questions/52229140/saving-several-variables-in-a-single-rds-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!