NSE challenge: break out of deparse(substitute(…))

房东的猫 提交于 2020-01-25 07:47:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!