[Bioc-devel] testing class and length of function args

Martin Morgan mtmorgan at fredhutch.org
Thu Jul 23 19:45:56 CEST 2015


On 07/23/2015 10:41 AM, Hervé Pagès wrote:
> Hi Mike,
>
> On 07/22/2015 04:13 PM, Michael Love wrote:
>> it's slightly annoying to write
>>
>> foo <- function(x) {
>>    if ( ! is.numeric(x) ) stop("x should be numeric")
>>    if ( ! length(x) == 2 ) stop("x should be length 2")
>>    c(x[2], x[1])
>> }
>
> That's a little bit kind of what stopifnot() is for:
>
>    stopifnot(is.numeric(x) && length(x) == 2)
>
> The error message you get is not perfect English but is very concise:
>
>    > foo(letters)
>    Error: is.numeric(x) && length(x) == 2 is not TRUE

Actually, separating the && conditions lead to more informative errors

 > foo = function(x) stopifnot(is.numeric(x), length(x) == 2)
 > foo(letters)
Error: is.numeric(x) is not TRUE
 > foo(1:5)
Error: length(x) == 2 is not TRUE

Martin

>
> H.
>
>>
>> i wonder if we could have some core functions that test the class and
>> the length in one and give the appropriate stop message.
>>
>> maybe this exists already
>>
>> -Mike
>>
>> _______________________________________________
>> Bioc-devel at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/bioc-devel
>>
>


-- 
Computational Biology / Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N.
PO Box 19024 Seattle, WA 98109

Location: Arnold Building M1 B861
Phone: (206) 667-2793



More information about the Bioc-devel mailing list