[R] using a variable name stored in another variable?
Chris Seidel
seidel at phaget4.org
Sun Feb 7 22:43:45 CET 2010
Hello,
I'm trying to figure out how to create a data object, and then save it
with a user-defined name that is input as a command line argument. I
know how to create the object and assign it the new name, however, I
can't figure out how to refer to the new name for a future operation
such as save(). The code below creates an object and uses assign() to
give it the user supplied name "MyName". However, since I don't know
what the new name is in advance, how do I refer to it in the save()
command? (the example below only saves an object with the name, not the
objec itself).
Is it some kind of dereference? Any ideas?
command:
cat myscript.r | R --vanilla --args MyName
script:
# get the command-line argument for the variable name
myobjectname <- commandArgs()[4]
# make some data
somedata <- matrix(rnorm(100),10,10)
# make a filename for the saved object
filename <- paste(myobjectname, ".RData", sep="")
# assign data to the new name
assign(myobjectname, somedata)
# save the object to disk
save(myobjectname, file=filename)
More information about the R-help
mailing list