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

R Y*_*oda 5 parameters r function ellipsis parameter-passing

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

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

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

> f(1, a = 1, b = 2)
[1] "a=1, b=2"
Run Code Online (Sandbox Code Playgroud)

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

# 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!
Run Code Online (Sandbox Code Playgroud)

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

[1] "a=1, b=2"
Run Code Online (Sandbox Code Playgroud)

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

编写自己的函数时如何使用R的省略号功能?

R 函数中点/句点的用法

将...参数传递给另一个函数

我可以删除...(点-点-点)中的元素并将其传递吗?

use*_*945 5

您可以通过使用 传递函数参数来完成此操作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))
Run Code Online (Sandbox Code Playgroud)