在函数调用中有条件地包含参数

编程入门 行业动态 更新时间:2024-10-26 20:33:00
本文介绍了在函数调用中有条件地包含参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

在函数调用中有条件地包含参数

本文发布于:2023-07-26 11:43:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1216009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中有   函数   条件   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!