[R] generic handling of NA and NaN and NULL
Spencer Graves
spencer.graves at pdf.com
Fri Feb 14 00:21:06 CET 2003
How about:
> f3 <- function(n){
+ n.pi <- (abs(n)<pi)
+ n.pi[is.na(n.pi)] <- F
+ n.pi
+ }
>
> f3(c(1, 5, NA))
[1] TRUE FALSE FALSE
>
Spencer Graves
Robin Hankin wrote:
> Hello everybody
>
>
> I have a generic problem which the following toy function illustrates:
>
> f <- function(n) {
> if(abs(n) < pi) {
> return(TRUE)
> } else {
> return(FALSE)
> }
> }
>
> I want it to return TRUE if abs(n)<pi and FALSE otherwise. f() is
> fine as far as it goes, but does not deal well with NA or NaN or NULL
> (I want these to signal some problem with the argument (ie return
> FALSE), but not to stop execution of f(). In particular, I want f()
> to pass R CMD check )-:
>
> R> f(NA)
> Error in if (abs(n) < pi) { : missing value where logical needed
>
> R> f(NULL)
> Error in abs(n) : non-numeric argument to function
>
>
> So, how best to patch f() up? The best I could come up with was:
>
> f2 <- function(n) {
> if(is.null(n)){return(FALSE)}
> if(is.na(n)){return(FALSE)}
> if(abs(n) < pi) {
> return(TRUE)
> } else {
> return(FALSE)
> }
> }
>
> This can't be the best way! Anyway, f2() isn't right: f2(numeric(0))
> fails; note that
>
> R> if(is.na(numeric(0))){print("asdf")}
>
> falls over. help.search("trap") was not very helpful. try() doesn't
> help either:
>
> R> try(if(1==NA){print("asdf")})
> Error in if (1 == NA) { : missing value where logical needed
>
>
>
> QUESTION: how to make f() not give an error under any circumstances?
>
>
>
>
>
>
More information about the R-help
mailing list