r - NSE 挑战:突破 deparse(substitute(...))
问题描述
让我们定义:
f <- function(x) deparse(substitute(x))
挑战:<something>
找到f(<something>)
返回"abc"
。当然,不包括f(abc)
.
使用“tidy NSE”,即准引用,这很容易。但是,根据 NSE 参考文献(1 , 2 , 3),这是不可能的,因为它是substitute
纯引用(与准引用相反)功能。
我想知道是否有任何模糊或无证的(不是那么罕见!)允许取消引用substitute
,因此是挑战。
解决方案
@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
推荐阅读
- mysql - 如何使用连接从表中搜索?
- dependencies - BitBake:我们可以在包名中使用 DEPENDS 吗?
- python - Django TemplateSyntaxError: 'endblock',预期为 'empty' 或 'endfor'。您是否忘记注册或加载此标签?
- html - 如何保持元素与可用空间对齐并以正确的空间垂直排列
- docker - Docker 在 nfs 上共享 workdir
- html - 如何从邮递员的以下响应中提取第一个 td 密码
- database - 迁移后测试数据库数据
- jquery - 如何增加自动完成搜索栏建议列表项(目前8个需要增加到16个)
- javascript - 三个 js:我想实现图像中显示的东西,我该怎么做,我尝试过 BoxGeomatry 和 planeGeomatry 也不一样
- php - php 使用 AJAX 从字符串创建文件