[R] using a variable name stored in another variable?

Chris Seidel seidel at phaget4.org
Mon Feb 8 21:30:35 CET 2010


Solved! Duncan Murdoch got it right:

> I think you want
>
> save(list=myobjectname, file= ...)
>
> assuming that the object has already been created with that name.  If 
> it hasn't, you'll need two steps:
> 
> assign( myobjectname, value)
> save(list=myobjectname, file=...)
[...]

This works great. If you have two objects in your environment, and you
only know the name of one, but it contains the name of the other. I had
done this because I'm processing Next Gen Sequencing data files which
are several gigabytes in size, but can be reduced to an object of
several megabytes, and saved to disk for analysis later with less
memory. This allows me to write a script which takes command line
arguments, including a name for the object I create and save.

I had looked in the R FAQ:

varname <- c("a", "b", "d")
eval(substitute(lm(y ~ x + variable),
                     list(variable = as.name(varname[1]))))

but between as.name, eval, and substitute, I was totally confused and
couldn’t get it right.

-Chris

> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Thomas Lumley
> Sent: Monday, February 08, 2010 10:09 AM
> To: Sharpie
> Cc: r-help at r-project.org
> Subject: Re: [R] using a variable name stored in another variable?
> 
> On Sun, 7 Feb 2010, Sharpie wrote:
> 
> > Chris Seidel wrote:
> >>
> >> 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().
> >>
> >> ..snip..
> >>
> >
> > You probably want the get() function:
> >
> >  get( myobjectname )
> >
> > The help page for get() has a note which states that it is the
> > compliment of assign().  Perhaps a similar note should be 
> added to the
> > help page for assign...
> 
> It's also FAQ 7.21.  Not quite as famous as 7.31, but still a
> good vintage.
> 
> 
>       -thomas
> 
> Thomas Lumley			Assoc. Professor, Biostatistics
> tlumley at u.washington.edu	University of Washington, Seattle



More information about the R-help mailing list