有没有方便、可维护的方法从函数中获取实际参数列表?

Is there a convenient, maintainable way to get the actual arguments list from within function?

假设我正在写一个带有签名

的函数foo
foo <- function (bar, baz, frobozz, quux = TRUE, frotz = 42) {
           # etc.
       }

如果在这个函数的主体中,我想获得函数在 运行 时间收到的实际参数的 命名列表 ,我可以定义

actual_args <- list(bar = bar, baz = baz, frobozz = frobozz, quux = quux,
                    frotz = frotz)

...但是这个分配很难维护,因为每次添加、删除或重命名参数时都需要修改它。 (更何况写起来也很繁琐。)

有没有一种方法可以初始化 actual_args,使其在函数签名的未来变化中保持不变?

?match.call

foo <- function(a, b, c, d, ...)
match.call()

foo(1, 2, 3, bar, e=baz())
# foo(a = 1, b = 2, c = 3, d = bar, e = baz())

这是一个调用对象,其第一个参数是被调用函数的名称(在本例中为foo)。其他参数是 unevaluated 参数 foo.

foo(1, 2, 3, bar, e=baz())[[1]]
# foo

foo(1, 2, 3, bar, e=baz())[[2]]
# 1

# the name of a variable
foo(1, 2, 3, bar, e=baz())[[5]]
# bar

# a function call
foo(1, 2, 3, bar, e=baz())[[6]]
# baz()

您可以在函数中使用 ls() 来获取所有已定义变量的列表。如果您在函数启动后立即调用它,您将获得所有参数的列表。然后,您可以使用 mget() 将这些值放入列表中。例如

foo<-function(a,b,c) {
    mget(ls())
}

这将适用于您的 do.call/mapply 场景

df <- data.frame(
    a=1:3,
    b=letters[1:3],
    c = runif(3))

do.call("mapply", c(foo, df))
#   [,1]      [,2]      [,3]     
# a 1         2         3        
# b factor,1  factor,1  factor,1 
# c 0.7845643 0.0297852 0.3611791