[R] the inverse of assign()

Duncan Murdoch murdoch.duncan at gmail.com
Tue Aug 27 23:53:14 CEST 2013


On 27/08/2013 4:38 PM, Rolf Turner wrote:
>
>
> Actually what's needed is "deparse(substitute(...))":
>
>       file = paste(deparse(substitute(x)),"csv",sep="."))
>
> I have no idea what "deparse" and "substitute" really mean; I just treat
> the forgoing as a black box/magic incantation.  It works.

In case anyone is interested:

Until you change them, arguments to functions are stored as "promises". 
  Those start out as an expression to evaluate, and a flag saying it 
hasn't been evaluated yet.  In most code, the first time you use the 
argument, it gets evaluated, the flag gets flipped, and the value gets 
saved.  After that you just see the value.

Using substitute(x) when x is a promise will return the expression, 
whether it has been evaluated or not.

But that expression is a bit of R language, it's not a character string. 
  Calling deparse() on it converts it to a character string 
representation of it.

So now you know.

Duncan Murdoch

>
>       cheers,
>
>       Rolf Turner
>
> On 28/08/13 09:19, Hadley Wickham wrote:
>> It's not really the inverse of assign (that's get), but I think you
>> want substitute.
>>
>> See http://adv-r.had.co.nz/Computing-on-the-language.html for more details.
>>
>> Hadley
>>
>> On Tue, Aug 27, 2013 at 4:13 PM, Robert Lynch<robert.b.lynch at gmail.com>  wrote:
>>> I am looking for a way to extract the name of a variable that has been
>>> passed into a function
>>>
>>> for example
>>>    foo<-function(x){
>>>    write.csv(x, file = paste(NAME(x), "csv", sep ="."))
>>> }
>>>
>>> is there a function "NAME" that would let the calls
>>> foo(bar)
>>>     write the file bar.csv
>>> and foo(stuff)
>>>     write the file stuff.csv
>>>
>>> Robert
>>>
>>>           [[alternative HTML version deleted]]
>>>
>>> ______________________________________________
>>> 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.
>>
>>
>
> ______________________________________________
> 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