Creating an unevaluated function call with unevaluated but changing arguments

六眼飞鱼酱① 提交于 2019-12-11 06:26:35

问题


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)

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)

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?


回答1:


When you do

> z <- n

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

Now compare with

> z <- quote(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)

and it will work as expected.



来源:https://stackoverflow.com/questions/42398790/creating-an-unevaluated-function-call-with-unevaluated-but-changing-arguments

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