NSE:是否可以从内部调用的函数中获取原始符号名称?

问题描述 投票:0回答:0

我怀疑答案是“不,你必须做一个标准的评估逃生舱”,但也许有人有一些想法。

想象一下编写一个使用非标准评估的函数来获取传递给它的对象的符号/名称:

inner_func <- function(inner_arg) {
    substitute(inner_arg)
}

inner_func(iris)
#> iris

当然,如果你在包装函数中调用

inner_func()
,这就会崩溃。

wrapper_func <- function(wrapper_arg) {
    inner_func(wrapper_arg)
}

wrapper_func(iris)
#> wrapper_arg

有没有办法从

inner_func()
中获取原始符号,即使它在另一个函数中传递,而不改变
inner_func()
的行为?
我知道这是可能的:

inner_func <- function(inner_arg) {
    evalq(as.symbol(inner_arg))
}

wrapper_func <- function(wrapper_func) {
    # Get the symbol as a Character
    obj_name <- deparse(substitute(wrapper_func))
    
    # eval(as.symbol()) inside inner_func() to turn it back into a symbol
    inner_func(obj_name)
}

wrapper_func(iris)
#> iris

但它涉及在

inner_func()
中做一些额外的处理,这会损害其最初被调用的能力:

inner_func(iris)

#> Error in as.vector(x, mode = mode) :
 'list' object cannot be coerced to type 'symbol'

如果可能的话,我更愿意在

wrapper_func()
中进行所有额外的处理。

r r-package
© www.soinside.com 2019 - 2024. All rights reserved.