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