【问题标题】:How to evaluate a string expression for multiple arguments?如何评估多个参数的字符串表达式?
【发布时间】:2022-06-14 23:19:15
【问题描述】:

我有一个 api 包装函数,除了一些定义的参数外,它还接受自定义参数。对于我的用例,此函数需要接受可变大小的自定义参数,因此我将这些参数构造为字符串表达式,其中包含要评估和传递此 API 的文档化运算符;我没有一个可重复的例子,因为这是一个定制的功能,但我希望这个概念可以让我们到达某个地方。我在将这些多个参数解析为构造时遇到问题。因此,例如下面是原始函数调用:

# original function
my_function(arg1 = this,
            arg2 = that,
            period = 12,
            # here are the two arguments that get passed in this case unique ids for specific data
            "0001q" %.d% c("1y", "2x", "3z"),
            "0002q" %.d% c("5u")
)

# my string expression
my_string <- "'0001q' %.d% c('1y', '2x', '3z'), '0002q' %.d% c('5u')"

# what I want to do
my_function(arg1 = this,
            arg2 = that,
            period = 12,
            # here are the two arguments that get passed in this case unique ids for specific data
            eval(parse(text = noquote(my_string)))
)

当我尝试上述操作时,我收到以下错误:

Error in parse(text = ... unexpected ','

我知道parse 只需要一个参数,在这种情况下是两个参数。有没有办法可以使用另一个函数或可以接受多个参数的解析变体来评估 my_string

【问题讨论】:

  • 需要使用字符串输入吗? R 具有强大的元编程能力,对于一个接受字符串而不是使用元编程的 API 通常是a mistake。 — 实际上,在您的情况下,您似乎只需要使用可变参数(即...)或向量/列表参数。

标签: r string parsing eval


猜你喜欢
  • 2016-04-24
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多