11

我想调用一个函数,但根据情况我可能会用额外的参数调用它。这是一个简单的例子:

FUN <- function(arg1 = "default1", arg2 = "default2", arg3 = "default3")
          print(list(arg1, arg2, arg3))


x1 <- "hi"
x2 <- TRUE
x3 <- 1:3

use.arg3 <- FALSE   # This will decide if `x3` is used or not.

if (use.arg3) {
   FUN(arg1 = x1, arg2 = x2, arg3 = x3)
} else {
   FUN(arg1 = x1, arg2 = x2)
}

虽然代码很清晰,但感觉有点多余。还想象一下,如果我有相似use.arg1use.arg2变量,我会有一个丑陋的可能性组合(8)......

我在下面发布了一个解决方案,但我发现它有点复杂,以至于我总是难以记住确切的语法。

如果你有更好的想法,谢谢分享。

4

2 回答 2

16

一种解决方案是do.call在构建具有适当参数的列表后使用:

do.call(FUN, c(list(arg1 = x1, arg2 = x2),   # unconditional args
               list(arg3 = x3)[use.arg3]))   # conditional arg

它可以很好地推广到多种条件:

do.call(FUN, c(list(arg1 = x1)[use.arg1]     # conditional arg
               list(arg2 = x2)[use.arg2]     # conditional arg
               list(arg3 = x3)[use.arg3]))   # conditional arg
于 2012-12-21T15:00:12.957 回答
7

Continuing the discussion from the comments on flodel's answer, here's an extension of my idea, out of curiosity. Not sure if it's really a feasible option:

FUN(arg1 = x1, arg2 = x2, arg3 = if(use.arg3) x3 else formals(FUN)$arg3)
于 2012-12-21T15:22:11.227 回答