使用未评估但变化的参数创建未评估的函数调用 [英] Creating an unevaluated function call with unevaluated but changing arguments
问题描述
先前的帖子显示了如何使用 quote()
创建一个未评估参数的函数调用:
A previous post shows how to use quote()
to create an unevaluated call to a function where the arguments are also unevaluated:
foo <-function(arg1,arg2){
value <- arg1 + arg2
}
foocall <- call("foo",arg1=quote(x),arg2=quote(y))
foocall
# foo(arg1 = x, arg2 = y)
如何保持这种质量,但允许更改arg1的规范。例如,我的环境中有两个命名对象n和m,有时我想越过一个,有时我想越过另一个。
How can I keep this quality but allow the specification of arg1 to change. E.g, I have two named objects n and m in my environment and sometimes I would like to pass over one and sometimes I would like to pass over the other.
## Named objects
n <- c(2,3)
m <- 3
## Case 1: i would like to pass over n
z <-n
call("foo", arg1=quote(z), arg2=quote(y))
## desired output
#foo(arg1 = n, arg2=y)
## Case 2: pass over m
z <- m
call("foo", arg1=quote(z), arg2=quote(y))
## desired output
#foo(arg1 = m, arg2=y)
我很难正确地表达我的问题,但我会这样说:如何为arg1分配一个变量,该变量可以更改但不求值,而仅对绑定对象的名称赋值?
I have a hard time to properly formulate my question, but I would state it like this: How can I assign to arg1 a variable that can change but doesn't evaluate 'all the way down', but only to the name of the object it is bound to?
推荐答案
这样做
> z <- n
评估右侧,因此符号 z
被分配了 n
的值,而不是符号 n $ c
the right-hand side is evaluated, so the symbol z
is assigned the value of n
, not the symbol n
itself.
> z
[1] 2 3
现在与
> z <- quote(n)
现在 z的值
是一个符号,即符号 n
。
Now the value of z
is a symbol, namely the symbol n
.
> z
n
因此,现在您可以这样做
Therefore now you can do
> call('foo', arg1=z, arg2=quote(y))
foo(arg1 = n, arg2 = y)
,它将按预期工作。
这篇关于使用未评估但变化的参数创建未评估的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!