本文介绍了NSE挑战:脱颖而出(substitute(...))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们定义:

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

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

The challenge: find <something> so that f(<something>) returns "abc". Excluding, of course, f(abc).

使用整洁的NSE"(即准引用),这非常容易.但是,根据NSE引用( 1 2 3 ),这是不可能的,因为substitute是纯引用(而不是准引用)功能.

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.

我想知道是否有任何晦涩或未记载的东西(不是那么不常见!)允许在substitute中取消报价,因此是一个挑战.

I wonder if there is anything obscure or undocumented (not that uncommon!) that allows to unquote in substitute, hence the challenge.

推荐答案

@Roland是正确的.由于未评估x,因此您无法为f提供不会被逐字转换为字符串的表达式. R中的准引号由bquote()处理,它具有.()机制,其作用类似于rlang的!!:

@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

这篇关于NSE挑战:脱颖而出(substitute(...))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 19:10