【发布时间】: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 的正确方法是什么?
【问题讨论】:
-
据我所知,由于
%>%的工作方式,没有干净的方法可以做你想做的事
标签: r dplyr substitution