Skip to content
Prev 198785 / 398506 Next

save an object by dynamicly created name

On Sun, Nov 1, 2009 at 7:48 PM, David Winsemius <dwinsemius at comcast.net> wrote:
Then a more convenient solution is to use saveObject() and
loadObject() of R.utils.  saveObject() does not save the name of the
object save.  If you want to save multiple objects, the wrap them up
in a list.  loadObject() does not assign variable, but instead return
them. Example:

library("R.utils");
x <- list(a=1,b=LETTERS,c=Sys.time());
saveObject(x, file="foo.Rbin");
y <- loadObject("foo.Rbin");
stopifnot(identical(x,y));

So, for the original example, I'd recommend:

library("R.utils");
path <- "data";
mkdirs(path);

for (i in 1:10) {
  m <- i:5;
  filename <- sprintf("m%02d.Rbin", i);
  saveObject(m, file=filename, path=path);
}

and loading the objects back as:

for (i in 1:10) {
  filename <- sprintf("m%02d.Rbin", i);
  m <- loadObject(filename, path=path);
  print(m);
}

/Henrik