[R] generic handling of NA and NaN and NULL

Robin Hankin r.hankin at auckland.ac.nz
Thu Feb 13 23:38:03 CET 2003

Hello everybody

I have a generic problem which the following toy function illustrates:

f <- function(n) {
  if(abs(n) < pi) {
  } else {
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(abs(n) < pi) {
  } else {

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?


Robin Hankin, Lecturer,
School of Geography and Environmental Science
Tamaki Campus
Private Bag 92019 Auckland
New Zealand

r.hankin at auckland.ac.nz
tel 0064-9-373-7599 x6820; FAX 0064-9-373-7042

More information about the R-help mailing list