2013-08-30 3 views
4

내 R 패키지 (S3 스타일)의 최종 사용자 함수가 인수 유효성을 검사하고 특정 유효성 검사가 실패 할 경우 사용자에게 유익한 오류 또는 경고를 제공하고자합니다.R 함수에 대한 반자동 인수 유효성 검사

이 될 것이라고 할 명백한 (그러나 지루한 및 유지 보수가 어려운) 방법 : 나는이 작업을 수행하는 멀지 않은 첫 번째로 해요 있으리라 믿고있어

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 
} 

. 그럼, 누구든지 그러한 검증 작업의 전부 또는 일부를 자동화하는 패키지를 제안 할 수 있습니까? 아니면, 각 함수 내에서 가능한 한 적은 수의 줄로 추함을 제한하는 일부 간결하고 일반적인 숙어가 없습니까?

감사합니다.

답변

5

stopifnot와 (과) 비슷한 항목 일 수 있습니다.

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

결과 :

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 
+2

참고 사항 [assertthat] (https : // githu b.com/hadley/assertthat)'stopifnot'과 같지만 더 나은 오류 메시지를 보여줍니다. – hadley

1

을 제공하지만 오류 메시지는 당신이 (기초적인 예)와 같은 도우미 함수를 작성할 수 있습니다 꽤 좋은하지 않습니다

> validate(1, "numeric", "positive") 
> validate(0, "numeric", "positive") 
Error in validate(0, "numeric", "positive") : non-positive arguments. 
관련 문제