问题
Let's define:
f <- function(x) deparse(substitute(x))
The challenge: find <something>
so that f(<something>)
returns "abc"
. Excluding, of course, f(abc)
.
With "tidy NSE", i.e. quasiquoting, this is very easy. However, according to the NSE references (1, 2, 3), it is impossible since substitute
is a pure quoting (as opposed to quasiquoting) function.
I wonder if there is anything obscure or undocumented (not that uncommon!) that allows to unquote in substitute
, hence the challenge.
回答1:
@Roland is correct. Because x
is not evaluated, there is no expression you can provide to f
that won't be converted to a string verbatim. Quasiquotation in base R is handled by bquote()
, which has a .()
mechanism that works similarly to rlang's !!
:
# 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
来源:https://stackoverflow.com/questions/58344944/nse-challenge-break-out-of-deparsesubstitute