首页 > 解决方案 > 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

标签: rargs

解决方案


对于多个参数,我们可以使用三个点 ( ...) 并且条件 withnargs将评估它

foo <- function(...) {

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

foo("a", "b")

foo("a", "b") 中的错误:仅输入 1 个参数

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

推荐阅读