Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a function in R with variable number of arguments,

Tags:

function

r

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.

like image 825
Lzz0 Avatar asked Feb 08 '18 20:02

Lzz0


People also ask

Can we pass a variable number of arguments to a function?

When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit.

Which function accepts a variable number of arguments?

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments.

How many number of arguments can be passed to a function?

Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.


2 Answers

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

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

[1] 15 
like image 146
KU99 Avatar answered Oct 01 '22 18:10

KU99


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)
like image 21
C. Braun Avatar answered Oct 01 '22 20:10

C. Braun