简体   繁体   English

如何通过match.call编程?

[英]How to program over match.call?

I'm trying to program over a function inside a package, but I'm stuck with the function internally using match.call() to parse one of its arguments. 我正在尝试对包中的函数进行编程,但是我在内部使用match.call()解析函数的一个参数而陷入了困境。

A super-simplified example of the function with the usual utilization could look like this: 具有通常用法的函数的超级简化示例如下所示:

f1 = function(x, y=0, z=0, a=0, b=0){ #lots of arguments not needed for the example
  mc = match.call()
  return(mc$x)
  #Returning for testing purpose.
  #Normally, the function later uses calls as character:
  r1 = as.character(mc$x[1])
  r2 = as.character(mc$x[2])
  #...
}
x1 = f1(x = foo(bar))
x1
# foo(bar)
class(x1)
# [1] "call"

In my case, I need to get the value of x from a variable ( value in the following code). 就我而言,我需要从变量中获取x的值(以下代码中的value )。 Expected utilisation of f1 is as following : f1预期利用率如下:

value = "foo(bar)" #this line could also be anything else
f1(x=some_magic_function(value))
# Expected result = foo(bar)
# Unwanted result = some_magic_function(value)

Unfortunately, match.call() always return the very input value. 不幸的是, match.call()总是返回非常输入的值。 I'm quite out of my league here so I only tried few functions. 我在这里已经很出类拔萃了,所以我只尝试了几次功能。

Is there any way I could trick match.call() so it could accept external variable ? 有什么办法可以欺骗match.call()使其可以接受外部变量吗?

Failed attempts so far: 到目前为止失败的尝试:

#I tried to create the exact same call using rlang::sym()
#This may not be the best way...
value = call("foo", rlang::sym("bar"))
value
# foo(bar)
class(value)
# [1] "call"
x1==value
# [1] TRUE

f1(x=value)
# value
f1(x=eval(value))
# eval(value)
f1(x=substitute(value))
# substitute(value)

There's nothing you can include as a parameter to f1 to make this work. 没有任何内容可以作为f1的参数来完成此工作。 Instead, you would dynamically need to build your call to f1 . 相反,您将需要动态地构建对f1的调用。 With base R you might do this with do.call . 对于基数R,您可以使用do.call进行此操作。

do.call("f1", list(parse(text=value)[[1]]))

or with rlang 或与Rlang

eval_tidy(quo(f1(!!parse_expr(value))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM