R函数的半自动化参数验证

bok*_*kov 4 validation r

我想在我的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
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Das*_*son 5

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

foo <- function(x){
    stopifnot(length(x) == 1, is.numeric(x))
    return(x)
}
Run Code Online (Sandbox Code Playgroud)

这使

> foo(c(1,3))
Error: length(x) == 1 is not TRUE
> foo("a")
Error: is.numeric(x) is not TRUE
> foo(3)
[1] 3
Run Code Online (Sandbox Code Playgroud)

  • 另见[assertthat](https://github.com/hadley/assertthat),它试图像`stopifnot`但有更好的错误信息. (2认同)