Semi-automation of argumentation for functions R

I would like the end-user functions in my R package (S3 style) to check their arguments and give user informational errors or warnings when a particular check fails.

The obvious (but tedious and incomprehensible) way to do this would be:

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 } 

I guess I'm not the first to do it. So, can anyone suggest a package that automates all or part of such verification tasks? Or, if it’s not, some short, general idioms that limit ugliness to as few lines as possible in each function?

Thanks.

+4
source share
2 answers

stopifnot may look like what you are looking for. Error messages will not be as pleasant though

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

which gives

 > foo(c(1,3)) Error: length(x) == 1 is not TRUE > foo("a") Error: is.numeric(x) is not TRUE > foo(3) [1] 3 
+5
source

You can write a helper function like this (simplest example):

 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.") ) } 

Results:

 > validate(1, "numeric", "positive") > validate(0, "numeric", "positive") Error in validate(0, "numeric", "positive") : non-positive arguments. 
+1
source

Source: https://habr.com/ru/post/1499869/


All Articles