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

后端 未结 1 1584
执念已碎
执念已碎 2021-01-14 12:32

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()         


        
相关标签:
1条回答
  • 2021-01-14 12:57

    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
    
    0 讨论(0)
提交回复
热议问题