首页 > 解决方案 > NSE 挑战:突破 deparse(substitute(...))

问题描述

让我们定义:

f <- function(x) deparse(substitute(x))

挑战:<something>找到f(<something>)返回"abc"。当然,不包括f(abc).

使用“tidy NSE”,即准引用,这很容易。但是,根据 NSE 参考文献(1 , 2 , 3),这是不可能的,因为它是substitute纯引用(与准引用相反)功能。

我想知道是否有任何模糊或无证的(不是那么罕见!)允许取消引用substitute,因此是挑战。

标签: rnsenon-standard-evaluation

解决方案


@Roland 是正确的。因为x没有被评估,所以您可以提供的任何表达式f都不会被逐字转换为字符串。基础 R 中的 Quasiquotation 由 处理bquote(),它具有.()与 rlang 类似的机制!!

# Quasiquotation with base R
f1 <- function(x) bquote( .(substitute(x)) + 5 )


# Quasiquotation with rlang
f2 <- function(x) rlang::expr( !!rlang::enexpr(x) + 5 )

e1 <- f1(y)               # y + 5
e2 <- f2(y)               # y + 5
identical(e1, e2)         # TRUE
eval(e1, list(y=10))      # 15

推荐阅读