简体   繁体   中英

How to get the variable name in a function call?

Sorry for my poor English but I can not think of a title that could concisely describe my problem, which is a little bit complicated than the title suggests.

Here is what I'd like to achieve:

In the global environment, one can get the name of a variable, say xyz , by calling deparse(substitute(xyz)) . I need to use this at several places in my code so I decided to make it a function: getVarName <- function(x){deparse(substitute(x))} .

Then I write some function myfunc in which I need to call getVarName :

myfunc <- function(x){cat(getVarName(x))}

Now here is the problem: when I call myfunc(y) , instead of printing out y , it still prints out x . I suspect it has something to do with the environment in which substitute() does the trick, but got no luck in that direction.

What do I have to do to make it right?

PS It'll be nice if some could edit the title with a better description of this question, thank you!

From what I saw while testing your code, it appears that deparse(substitute(x)) will only print out the name of the variable which was immediately below it in the call stack. In your example:

getVarName <- function(x){ deparse(substitute(x)) }
myfunc <- function(x){ cat(getVarName(x)) }
myfunc(y)

The call to getVarName() is processing a variable from myfunc() which was called x . In effect, the variable y which you passed is not part of the call stack anymore.

Solution:

Just use deparse(substitute(x)) directly in the function where you want to print the name of the variable. It's concise, and you could justify not having a helper function as easily as having one.

It is typically the kind of functional programmming problem where you can use a decorator:

decorator = function(f)
{
     function(...)
     {
         print(as.list(match.call()[-1]))
         f(...)
     }
}

foo = function(x,y,z=2) paste0(x,y,z)
superFoo = decorator(foo)

Results:

> xx=34 
> superFoo('bigwhale',xx)
[[1]]
[1] "bigwhale"

[[2]]
xx

[1] "bigwhale342"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM