[R] using a variable name stored in another variable?
Duncan Murdoch
murdoch at stats.uwo.ca
Mon Feb 8 00:19:42 CET 2010
On 07/02/2010 6:05 PM, Chris Seidel wrote:
> Hi Charlie,
>
> get() will return the contents (value) of a variable. But what I want is
> to save the named object. Something like save(get(myobjectname), ...)
> doesn't work.
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=...)
These could be wrapped in local( { ... } ) if you are worried that
myobjectname might be the name of an object you want to keep. For example,
x <- 1 # Create a variable I don't want to mess with
name <- "x" # choose a name to save under
local({ assign(name, 2) ; save(list=name, file="test.Rdata") })
# That created test.Rdata with x equal to 2
Duncan Murdoch
>
> In the environment, is that object of interest, and a variable which
> holds the name of the object of interest. If you don't know the name of
> the object, but only the variable which contains it's name, how do you
> use that information to save the object?
>
> -Chris
> ________________________________________
> From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On
> Behalf Of Sharpie [chuck at sharpsteen.net]
> Sent: Sunday, February 07, 2010 4:13 PM
> To: r-help at r-project.org
> Subject: Re: [R] using a variable name stored in another variable?
>
> 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...
>
> Hope this helps!
>
> -Charlie
> --
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list