Antoine C.
Antoine C.

Reputation: 3952

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

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)

Upvotes: 4

Views: 837

Answers (1)

Ekaba Bisong
Ekaba Bisong

Reputation: 2982

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

Upvotes: 7

Related Questions