Search code examples
rmatlabargumentsenvironment

Nargin function in R (number of function inputs)


Goal

I am trying to create a function in R to replicate the functionality of a homonymous MATLAB function which returns the number of arguments that were passed to a function.

Example

Consider the function below:

addme <- function(a, b) {
    if (nargin() == 2) {
        c <- a + b
    } else if (nargin() == 1) {
        c <- a + a
    } else {
        c <- 0
    }
    return(c)
}

Once the user runs addme(), I want nargin() to basically look at how many parameters were passed―2 (a and b), only 1 (a) or none―and calculate c accordingly.

What I have tried

After spending a lot of time messing around with environments, this is the closest I ever got to a working solution:

nargin <- function() {
    length(as.list(match.call(envir = parent.env(environment()))))
}

The problem with this function is that it always returns 0, and the reason why is that I think it's looking at its own environment instead of its parent's (in spite of my attempt of throwing in a parent.env there).

I know I can use missing() and args() inside addme() to achieve the same functionality, but I'll be needing this quite a few other times throughout my project, so wrapping it in a function is definitely something I should try to do.

Question

How can I get nargin() to return the number of arguments that were passed to its parent function?


Solution

  • You could use

    nargin <- function() {
      if(sys.nframe()<2) stop("must be called from inside a function")
      length(as.list(sys.call(-1)))-1
    }
    

    Basically you just use sys.call(-1) to go up the call stack to the calling function and get it's call and then count the number of elements and subtract one for the function name itself.