从函数内部,我如何访问其调用中使用的表达式?

时间:2015-05-22 13:20:33

标签: r dplyr substitution

在函数内部,我想使用调用中使用的对象的名称。例如,如果我在对象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

使用写我的函数的正确方法是什么?

1 个答案:

答案 0 :(得分:-1)

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