Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving several variables in a single RDS file

Tags:

r

save

datastore

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

like image 685
Mehdi Zare Avatar asked Sep 07 '18 20:09

Mehdi Zare


1 Answers

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
like image 185
ichbinallen Avatar answered Sep 27 '22 23:09

ichbinallen