[R] deparse substitute

Duncan Murdoch murdoch.duncan at gmail.com
Wed Jan 9 11:58:36 CET 2013


On 13-01-09 5:03 AM, Berry Boessenkool wrote:
>
>
> Hi,
>
> I'm writing a function that needs the input names (as characterstrings) as part of the output.
> With deparse(substitute( ) ) that works fine, until I replace all zeros with 0.001 (log is calculated at some time):
>
> tf <- function(input) { input[input==0] <- 0.001 ;   deparse(substitute(input)) }
> myguess <- 42
> tf(myguess)     # not "myguess", but "42"
>
>
> Now when I extract the input names before replacing the zeros, this works:
>
> tf <- function(input) { out <- deparse(substitute(input)) ;   input[input==0] <- 0.001 ;   out }
> tf(myguess)     # correct: "myguess"
> myguess <- 0 ; tf(myguess) # ditto
>
>
> While I did find a workaround, I'm still wondering why this happens.
> Any hints on where to start reading?

Probably the R Language definition, section 2.1.8.  The basic 
explanation for the behaviour you see is that deparse(substitute(input)) 
acts on the "input" promise object, looking at its expression slot. It's 
not doing any magic examination of the context in which it was 
originally defined.

Once you modify it, it is no longer a promise, and so it has no 
expression slot.

Duncan Murdoch




More information about the R-help mailing list