不使用参数时运行具有多个参数的函数 [英] Running a function with multiple arguments when an argument is not used
问题描述
我认为我的问题可以变得非常普通和简单,这样我就不会给出我要实现的具体功能.
I think my question can be made quite generic and simple, so that I will not give the concrete function that I am trying to make.
我有一个根据其第一个参数更改其行为的函数:
I have a function that changes its behaviour according to its first argument:
example <- function(arg1 = T,
arg2 = NULL,
arg3,
...) {
if (arg1 != T) {
final <- bind_rows(arg2)
} else{
list1 <- list(...)
final <- bind_rows(list1, arg3)
}
return(final)
}
我的问题是,如果我运行 example(arg1 = T,arg3 = x,c(A,B),c(C,D))
,考虑到我函数的用户可能不会为 arg2
写任何内容,我有问题. c(A,B)
最终没有被视为 list1
的第一个元素(我想它已分配给 arg2
,然后在函数),我有 bind_rows(c(C,D),x)
作为输出,而不是 bind_rows(c(A,B),c(C,D),x)
.
My issue is that if I run example(arg1 = T, arg3 = x, c(A,B), c(C,D))
, considering that the user of my function probably won't write out anything for arg2
, I have a problem. c(A,B)
ends up not being considered the first element of list1
(I guess it is assigned to arg2
and then goes unused in the function) and I have bind_rows(c(C,D), x)
as the output, instead of bind_rows(c(A,B), c(C,D), x)
.
考虑到该功能不是供个人使用,而是用于较大的包装,如何解决?
How can this be fixed, considering that the function is not for personal use, but for a larger package?
推荐答案
将arg2放入 ...
example <- function(arg1 = T,
arg3,
...) {
args <- list(...)
if (is.null(args$arg2) & arg1==F) {stop("arg2 needed when arg1==F")}
if (arg1 != T) {
final <- list(arg2)
} else{
list1 <- list(...)
final <- list(list1, arg3)
}
return(final)
}
这篇关于不使用参数时运行具有多个参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!