简体   繁体   English

如何在函数调用中获取变量名?

[英]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)) . 在全局环境中,可以通过调用deparse(substitute(xyz))来获取变量的名称,比如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))} . 我需要在我的代码中的几个地方使用它,所以我决定使它成为一个函数: getVarName <- function(x){deparse(substitute(x))}

Then I write some function myfunc in which I need to call getVarName : 然后我写了一些函数myfunc ,我需要在其中调用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 . 现在问题是:当我调用myfunc(y)时,它仍然打印出x ,而不是打印出y I suspect it has something to do with the environment in which substitute() does the trick, but got no luck in that direction. 我怀疑它与环境有关,其中substitute()可以解决问题,但在那个方向上没有运气。

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! PS如果有人可以通过更好地描述这个问题来编辑标题,那将是很好的,谢谢!

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. 从我在测试代码时看到的内容来看, deparse(substitute(x))似乎只打印出调用堆栈中紧邻其下方的变量的名称。 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 . getVarName()的调用是从myfunc()处理一个名为x的变量。 In effect, the variable y which you passed is not part of the call stack anymore. 实际上,您传递的变量y不再是调用堆栈的一部分。

Solution: 解:

Just use deparse(substitute(x)) directly in the function where you want to print the name of the variable. 只需在要打印变量名称的函数中直接使用deparse(substitute(x)) 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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