解析,用三点参数替换 [英] Deparse, substitute with three-dots arguments
问题描述
让我们考虑一个典型的 deparse(substitute(
R call:
Let consider a typical deparse(substitute(
R call:
f1 <-function(u,x,y)
{print(deparse(substitute(x)))}
varU='vu'
varX='vx'
varY='vy'
f1(u=varU,x=varX,y=varY)
结果是
[1] "varX"
这是我们期望和想要的.
which is what we expect and we want.
然后,麻烦来了,我尝试使用 ...
参数获得类似的行为,即
Then, comes the trouble, I try to get a similar behaviour using the ...
arguments i.e.
f2 <- function(...)
{ l <- list(...)
x=l$x
print(deparse(substitute(x))) ### this cannot work but I would like something like that
}
毫不奇怪,这不起作用:
That, not surprisingly, does not work :
f2(u=varU,x=varX,y=varY)
[1] "\"vx\"" ### wrong ! I would like "varX"
我尝试使用不同的解决方案组合来获得预期的行为,但没有一个提供给我预期的结果,而且似乎我对懒惰的评估仍然不够清楚,无法在合理的时间内找到操作方法.
I tried to get the expected behaviour using a different combination of solutions but none provides me what expected and it seems that I am still not clear enough on lazy eval to find myself the how-to in a resonable amount of time.
推荐答案
您可以通过执行获得所有未评估参数的列表
You can get the list of all unevaluated arguments by doing
match.call(expand.dots = FALSE)$...
或者,如果你只有有点参数,通过
Or, if you only have dot arguments, via
as.list(match.call()[-1L])
这将为您提供一个命名列表,类似于 list(...)
,但采用未评估的形式(类似于 substitute
对单个参数所做的事情).
This will give you a named list, similarly to list(...)
, but in its unevaluated form (similarly to what substitute
does on a single argument).
如果您愿意使用 {rlang} 包,另一种方法是使用 rlang::quos(...)
,它以稍微不同的形式返回类似的结果.
An alternative is using rlang::quos(...)
if you’re willing to use the {rlang} package, which returns a similar result in a slightly different form.
这篇关于解析,用三点参数替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!