Search code examples
rargs

R Code ignored nargs() if statement


Cannot figure out why R is ignoring nargs() in following

foo <- function(x=NULL) {

  if (nargs() > 1){
    stop("Enter 1 argument only")
  }
  cat("call was ", deparse(match.call()), "\n", sep = "")
}

When I execute foo("a","b"), I get Error in foo("a", "b") : unused argument ("b") instead of Enter 1 argument only.

Please advise


Solution

  • For multiple arguments, we can use three dots (...) and the condition with nargs will evaluate it

    foo <- function(...) {
    
     if (nargs() > 1){
      stop("Enter 1 argument only")
     }
      cat("call was ", deparse(match.call()), "\n", sep = "")
     }
    
    foo("a", "b")
    

    Error in foo("a", "b") : Enter 1 argument only

    foo("a")
    #call was foo("a")