在函数调用中有条件地包含参数 [英] conditional inclusion of arguments in a function call

查看:64
本文介绍了在函数调用中有条件地包含参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个函数,但是根据情况,我可能会使用其他参数来调用它,也可能不使用.这是一个简单的示例:

I want to call a function but depending on the situation I might call it with extra arguments or not. Here is a simple example:

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.arg1 use.arg2 变量,那么我将遇到各种各样的可能性(8)...

While the code is clear, it feels a little redundant. Also imagine that if I had similar use.arg1 and use.arg2 variables, I would have an ugly mix of possibilities (8)...

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

I have a solution posted below but I find it a little complicated, to the point that I always struggle to remember the exact syntax.

如果您有更好的主意,谢谢您的分享.

If you have a better idea, thank you for sharing.

推荐答案

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

One solution is to use do.call after building a list with the proper arguments:

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

它可以很好地推广到多种情况:

And it generalizes well to multiple conditions:

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

这篇关于在函数调用中有条件地包含参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆