在R中建立函式时,通常会指定类似
function(x,y){
}
Run Code Online (Sandbox Code Playgroud)
这意味着只需要两个参数。但是,如果未指定参数数量(一种情况下,我必须使用两个参数,而另一种情况下,我必须使用三个或更多参数),我们该如何处理这个问题?我对编程很陌生,因此示例将不胜感激。
d <- function(...){
x <- list(...) # THIS WILL BE A LIST STORING EVERYTHING:
sum(...) # Example of inbuilt function
}
d(1,2,3,4,5)
[1] 15
Run Code Online (Sandbox Code Playgroud)
您可以...用来指定其他数量的参数。例如:
myfun <- function(x, ...) {
for(i in list(...)) {
print(x * i)
}
}
> myfun(4, 3, 1)
[1] 12
[1] 4
> myfun(4, 9, 1, 0, 12)
[1] 36
[1] 4
[1] 0
[1] 48
> myfun(4)
Run Code Online (Sandbox Code Playgroud)