Skip to content
Prev 198918 / 398506 Next

save an object by dynamicly created name

Hi Henrik and David,

Thank you very much for your suggestions. I found both meet my needs.

In the following code,  I found save(obj,file=pathname) would save the
content into an object called obj. 

path <- "~/";
dir.create(path);

for (i in 1:10) {
  assign( paste("m", i, sep=""),  i:5)
  filename <- sprintf("m%02d.Rdta", i)
  pathname <- file.path(path, filename)
  obj =get(paste("m", i, sep=""))
  save(obj, file=pathname)
}

A tweak to this would be

path <- "~/";
dir.create(path);

for (i in 1:10) {
  assign( paste("m", i, sep=""),  i:5)
  filename <- sprintf("m%02d.Rdta", i)
  pathname <- file.path(path, filename)
  save(list = paste("m", i, sep=""), file=pathname)
}


Thanks a lot

Hao

-----Original Message-----
From: henrik.bengtsson at gmail.com [mailto:henrik.bengtsson at gmail.com] On
Behalf Of Henrik Bengtsson
Sent: Monday, November 02, 2009 12:34 AM
To: David Winsemius
Cc: r-help at r-project.org; jeffc
Subject: Re: [R] save an object by dynamicly created name

On Sun, Nov 1, 2009 at 9:18 PM, David Winsemius <dwinsemius at comcast.net>
wrote:
,
That comment was not for the OP, but for saveObject()/loadObject() in
general.
Nope, the whole point of using saveObject()/loadObject() is to save
the objects/values without their names that you happens to choose in
the current session, and to avoid overwriting existing ones in your
next session. My example could also have been:

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

If you really want to attach the elements of the saved list, do:

attachLocally(loadObject("foo.Rbin"));
num 1
chr [1:26] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" ...
POSIXct[1:1], format: "2009-11-01 21:30:41"
is
times
http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-
variable_003f

My personal take on assign() and get() is that if you find yourself
using them (at this level), there is a good chance there exists a
better solution that you should use instead.

My $.02

/H
as
http://old.nabble.com/save-an-object-by-dynamicly-created-name-tp26155437p26
155437.html