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

Call an R function with run-time generated ellipsis arguments (dot-dot-dot / three dots)

我想调用一个使用 ...(省略号)参数的 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?

您可以通过使用 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))