Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know the number of arguments of a function?

Tags:

r

How can we know how many arguments a function take?

For instance, for a given function f, I'd like to do:

if (arg_number(f) == 0)
  f()
else if (arg_number(f) == 1)
  f(FALSE)
like image 652
Antoine C. Avatar asked Oct 20 '25 09:10

Antoine C.


1 Answers

nargs(): will check the number of arguments from within the function
The Number of Arguments to a Function

Edit:
formals will give access to the arguments of the function

> f <- function(x, y, z) x + y + z
> formals(f)
> $x
> $y
> $z

Update: (from @Spacedman)
To know the number of arguments,

> length(formals(f))
> [1] 3

Also,

> length(formalArgs(f))
> [1] 3
like image 163
Ekaba Bisong Avatar answered Oct 21 '25 22:10

Ekaba Bisong