4

我希望我的 R 包(S3 风格)中的最终用户函数验证他们的参数,并在特定有效性检查失败时向用户提供信息性错误或警告。

这样做的明显(但乏味且不可维护)的方法是:

foo<-function(aa,bb,cc,dd){
  if(length(aa)!=1) stop("The argument 'aa' must have a single value");
  if(!is.numeric(aa)) stop("The argument 'aa' must be numeric");
  if(!is.character(bb)) stop("The argument 'bb' must be a character");
  if(length(bb)>=4||length(bb)<=2) stop("The argument 'bb' must be a vector with a length between 2 and 4");
  if(!is.recursive(cc)) stop("The argument 'cc' must be a list-like object");
  if(!is.integer(dd)) stop("The argument 'dd' must contain only integers");
  if(any(dd<aa)) stop("All values in the argument 'dd' must be greater than the value of argument 'aa'");
  ## ...and so on
}

我假设我不是第一个这样做的人。那么,任何人都可以建议一个可以自动执行全部或部分此类验证任务的软件包吗?或者,如果做不到这一点,一些简洁的通用习语会将丑陋限制在每个函数中尽可能少的行?

谢谢。

4

2 回答 2

5

stopifnot可能与您正在寻找的相似。错误消息不会那么好

foo <- function(x){
    stopifnot(length(x) == 1, is.numeric(x))
    return(x)
}

这使

> foo(c(1,3))
Error: length(x) == 1 is not TRUE
> foo("a")
Error: is.numeric(x) is not TRUE
> foo(3)
[1] 3
于 2013-08-30T20:58:21.937 回答
1

您可以编写这样的辅助函数(基本示例):

validate <- function(x, ...){
    for(s in c(...)) switch(s,
        lengthone = if(length(x)!=1) stop("argument has length != 1."),
        numeric = if(!all(is.numeric(x))) stop("non-numeric arguments."),
        positive = if(any(x <= 0)) stop("non-positive arguments."),
        nonmissing = if(any(is.na(x))) stop("Missing values in arguments.")
    )
}

结果:

> validate(1, "numeric", "positive")
> validate(0, "numeric", "positive")
Error in validate(0, "numeric", "positive") : non-positive arguments.
于 2013-08-30T22:58:24.373 回答