Creating a function in R with variable number of arguments,

前端 未结 2 987
忘掉有多难
忘掉有多难 2020-12-18 21:19

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

相关标签:
2条回答
  • 2020-12-18 21:44

    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)
    
    0 讨论(0)
  • 2020-12-18 22:00
    d <- function(...){
        x <- list(...) # THIS WILL BE A LIST STORING EVERYTHING:
        sum(...)       # Example of inbuilt function
    }
    
    d(1,2,3,4,5)
    
    [1] 15 
    
    0 讨论(0)
提交回复
热议问题