I want to write a function in R which grabs the name of a variable from the context of its caller's caller. I think the problem I have is best understood by asking how to compose deparse
and substitute
. You can see that a naive composition does not work:
# a compose operator
> `%c%` = function(x,y)function(...)x(y(...))
# a naive attempt to combine deparse and substitute
> desub = deparse %c% substitute
> f=function(foo) { message(desub(foo)) }
> f(log)
foo
# this is how it is supposed to work
> g=function(foo) { message(deparse(substitute(foo))) }
> g(log)
log
I also tried a couple of variations involving eval.parent
but with no luck. Any help is appreciated.
Clarification: I'm not looking for a synonym for deparse(substitute(...))
, e.g. match.call()[[2]]
- what I'm looking for is a way to define a function
desub = function(foo) {
...
# What goes here?
}
such that the definition of f
above produces the same answer as g
. It should look like this:
> f=function(foo) { message(desub(foo)) }
> f(log)
log
Perhaps match.call
could be of use in the body of desub
above, but I'd like to know how. Thanks!
Thanks to @egnha and @akrun for the brave attempts. After playing around a bit I found a solution that works.
This fragment:
gives:
Update:
With help from Mark Bravington on the R-devel list, I was able to generalize this to multiple frames. I thought I should post it here, because it's a bit more useful than the above, and because there was a tricky workaround involving (possibly buggy?) behavior in
parent.frame()
.