Creating a function in R with variable number of arguments,

巧了我就是萌 提交于 2020-06-11 17:17:26

问题


When creating a function in R, we usually specify the number of argument like

function(x,y){
}

That means it takes only two arguments. But when the numbers of arguments are not specified (For one case I have to use two arguments but another case I have to use three or more arguments) how can we handle this issue? I am pretty new to programming so example will be greatly appreciated.


回答1:


d <- function(...){
    x <- list(...) # THIS WILL BE A LIST STORING EVERYTHING:
    sum(...)       # Example of inbuilt function
}

d(1,2,3,4,5)

[1] 15 



回答2:


You can use ... to specify an additional number of arguments. For example:

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)


来源:https://stackoverflow.com/questions/48694626/creating-a-function-in-r-with-variable-number-of-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!