使用运行时生成的省略号参数调用R函数(点 - 点 - 点/三点)

时间:2017-11-17 23:50:01

标签: r function parameters parameter-passing ellipsis

我想调用一个使用...(省略号)参数的R函数来支持未定义数量的参数:

f <- function(x, ...) {
  dot.args <- list(...)
  paste(names(dot.args), dot.args, sep = "=", collapse = ", ")
}

我可以调用此函数传递在设计时预定义的实际参数,例如: G:

> f(1, a = 1, b = 2)
[1] "a=1, b=2"

如何传递仅在运行时知道的...的实际参数(例如来自用户的输入)?

# let's assume the user input was "a = 1" and "b = 2"
# ------
# If the user input was converted into a vector:
> f(1, c(a = 1, b = 2))
[1] "=c(1, 2)"                # wrong result!
# If the user input was converted into a list:
> f(1, list(a = 1, b = 2))
[1] "=list(a = 1, b = 2)"     # wrong result!

动态生成的f调用的预期输出应为:

[1] "a=1, b=2"

我发现了一些关于如何使用...的现有问题,但他们没有回答我的问题:

How to use R's ellipsis feature when writing your own function?

Usage of Dot / Period in R Functions

Pass ... argument to another function

Can I remove an element in ... (dot-dot-dot) and pass it on?

1 个答案:

答案 0 :(得分:3)

您可以使用do.call传递函数参数来完成此操作。首先使用as.list强制列出。

例如

input <- c(a = 1, b = 2)
do.call(f,  as.list(input))

input <- list(a = 1, b = 2)
do.call(f,  as.list(input))