【问题标题】:From inside a function, how can I have access to an expression used in its call?从函数内部,如何访问在其调用中使用的表达式?
【发布时间】:2015-05-22 13:20:32
【问题描述】:

在函数内部,我想使用调用中使用的对象的名称。例如,如果我正在测试对象 foo 和对象 bar 之间的身份,我希望能够打印 2 希望能够打印:

foo is not the same as bar

即使我的函数是用其他名称定义的参数。

我知道如何使用substitute 做到这一点。不幸的是,substitute 在几种情况下会中断:当使用dplyr 的%>% 链接函数时;或更一般地,首先是函数调用。

test.equal <- function(a, b) if(!identical(a,b)) cat(
  substitute(a),
  'is not the same as',
  substitute(b)
)
object1 <- 'lkjlkj'
object2 <- 1:10
test.equal(object1, object2)    # works as intended
object1 %>% test.equal(object2) # does not : prints '.' for object 1
test.equal(object1, object2^2)  # error: cat does not print 'language'
                                # and if we use as.character to force evaluation...

test.equal2 <- function(a, b){
  charb <- as.character(substitute(b))
  if(!identical(a,b)) cat(
   substitute(a),
   'is not the same as',
   charb
  )
}

test.equal2(object1, object2^2) # prints ^ object2 2 instead of object2^2

使用 write my function 的正确方法是什么?

【问题讨论】:

  • 据我所知,由于%&gt;% 的工作方式,没有干净的方法可以做你想做的事

标签: r dplyr substitution


【解决方案1】:

这是通过 deparse(substitute(a)) 实现的,它将返回您在函数调用中输入的变量的名称 (foo)。

【讨论】:

  • 这仍然会返回“。” dplyr 链中的变量名。
  • 这是部分答案:它解决了test.equal(object1, object2^2) 的问题,但不能解决object1 %&gt;% test.equal(object2)test 的问题
  • 可能是这样,但 OP 专门询问如何从 function 中检索,而不是从 magrittr 或 pipeR 对闭包所做的任何事情。
猜你喜欢
  • 1970-01-01
  • 2017-12-11
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多