【问题标题】:Force-evaluate function argument in order to "trick" substitute()?强制评估函数参数以“欺骗”替代()?
【发布时间】:2021-11-08 12:11:34
【问题描述】:

假设我有一个来自 R 包的函数,我想将其包装在一个闭包中,以方便和提高代码可读性。为简单起见,我们假设函数如下所示:

fun <- function(text) {
    as.character(substitute(text))
}

当我从控制台调用该函数时,例如

fun(text = "bar")

返回值是"bar",在我的例子中是期望的行为。函数按原样编写的原因是,以防万一我调用

fun(text = bar)

输出也是"bar"。只是为了上下文。这个函数显然不是我自己写的,我只是想用它。

问题:当我从函数中调用fun 时,例如

fun2 <- function(foo) {
    fun(text = foo)
}
fun2(foo = "bar")

无论我在对fun2 的调用中分配给foo 的内容,输出将始终为"foo" 而不是“bar”。 Ofc 我知道substitute() 是这样工作的,但这使得以编程方式使用函数fun 成为不可能(或者至少非常讨厌?)。

我的问题:有没有办法在不重写fun的情况下实现所需的行为?

提前非常感谢:)

【问题讨论】:

    标签: r nse


    【解决方案1】:

    您可以在 fun2 内部构造调用并对其进行评估:

    fun2 <- function(foo) {
      eval(call("fun", foo))
    }
    
    fun2(foo = "bar")
    #> [1] "bar"
    

    这里的问题是,如果你通过bar unquoted,它现在不再起作用:

    fun2(foo = bar)
    #> Error in eval(call("fun", foo)) : object 'bar' not found
    

    所以你需要类似的东西:

    fun2 <- function(foo) {
      if(exists(as.character(substitute(foo)), parent.frame())) {
        eval(call("fun", foo))
      } else {
        eval(call("fun", as.character(substitute(foo))))
      }
    }
    

    现在无论哪种方式都可以:

    fun2(foo = "bar")
    #> [1] "bar"
    
    fun2(foo = bar)
    #> [1] "bar"
    

    这里的问题是,如果bar确实存在,那么它会被解释为bar的值,所以我们有:

    fun2(foo = "bar")
    #> [1] "bar"
    
    fun2(foo = bar)
    #> [1] "bar"
    
    bar <- 1
    
    fun2(foo = bar)
    #> [1] "1"
    

    这可能不是你想要的。

    但是,如果您打算这样做,那么调用fun 可能根本没有意义。也许最简单的事情是

    fun2 <- function(foo) {
      as.character(match.call()$foo)
    }
    
    fun2("bar")
    #> [1] "bar"
    
    fun2(bar)
    #> [1] "bar"
    
    bar <- 1
    
    fun2(bar)
    #> [1] "bar"
    

    【讨论】:

    • 非常感谢!嗯,这并没有我想象的那么难。实际上,您的第一个解决方案已经为我做了,因为我不在乎 fun2(bar) 是否返回与 fun2("bar") 相同的结果。对于我的用例,能够使用fun2("bar") 非常好:)
    猜你喜欢
    • 2015-08-02
    • 2019-07-02
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2011-07-27
    • 1970-01-01
    相关资源
    最近更新 更多