繁体   English   中英

如何通过match.call编程?

[英]How to program over match.call?

我正在尝试对包中的函数进行编程,但是我在内部使用match.call()解析函数的一个参数而陷入了困境。

具有通常用法的函数的超级简化示例如下所示:

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"

就我而言,我需要从变量中获取x的值(以下代码中的value )。 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)

不幸的是, match.call()总是返回非常输入的值。 我在这里已经很出类拔萃了,所以我只尝试了几次功能。

有什么办法可以欺骗match.call()使其可以接受外部变量吗?

到目前为止失败的尝试:

#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)

没有任何内容可以作为f1的参数来完成此工作。 相反,您将需要动态地构建对f1的调用。 对于基数R,您可以使用do.call进行此操作。

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

或与Rlang

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

暂无
暂无

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

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