Save object using variable with object name

Posted by FBE on Stack Overflow See other posts from Stack Overflow or by FBE
Published on 2012-06-18T13:55:51Z Indexed on 2012/06/18 15:16 UTC
Read the original article Hit count: 239

Filed under:
|

I'm wondering what an easy way is to save an object in R, using a variable objectName with the name of the object to be saved. I want this to easy save objects, with their name in the file name.

I tried to use get, but I didn't manage to save the object with it's original object name.

Example:

If I have the object called "temp", which I want to save in the directory "dataDir". I put the name of the object in the variable "objectName".

Attempt 1:

objectName<-"temp"
save(get(objectName), file=paste(dataDir, objectName, ".RData", sep=""))
load(paste(dataDir, objectName, ".RData", sep=""))

This didn't work, because R tries to save an object called get(objectName), instead of the result of this call. So I tried the following:

Attempt 2:

objectName<-"temp"
object<-get(objectName)
save(object, file=paste(dataDir, objectName, ".RData", sep=""))
load(paste(dataDir, objectName, ".RData", sep=""))

This obviously didn't work, because R saves the object with name "object", and not with name "temp". After loading I have a copy of "object", instead of "temp". (Yes, with the same contents...but that is not what I want :) ). So I thought it should be something with pointers. So tried the following:

Attempt 3:

objectName<-"temp"
object<<-get(objectName)
save(object, file=paste(dataDir, objectName, ".RData", sep=""))
load(paste(dataDir, objectName, ".RData", sep=""))

Same result as attempt 2. But I'm not sure I'm doing what I think I'm doing.

What is the solution for this?

© Stack Overflow or respective owner

Related posts about r

    Related posts about save