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