Skip to content
Prev 261136 / 398502 Next

NaN, Inf to NA

One of my beefs about the S3 and S4 object systems is
that the "default" or "ANY" method is often used for
both the the simple (atomic, matrix of atomic, named
atomic, etc.) classes and for any class the writer
hasn't thought of.  It can be difficult to write code
that works well in both cases.

I've tried just omitting the default method to avoid
the problem.  I end up writing a lot of identical
methods for the the simple cases, but I get the error
checking that I want.  E.g.,

  > omitZero <- function(x) UseMethod("omitZero")
  > omitZero.numeric <- function(x)x[x!=0]
  > omitZero.integer <- function(x)x[x!=0]
  > omitZero.complex <- function(x)x[x!=0]
  > omitZero(c(1L,2L,0L,4L))
  [1] 1 2 4
  > omitZero(c(TRUE,TRUE,FALSE))
  Error in UseMethod("omitZero") : 
    no applicable method for 'omitZero' applied to an object of class
"logical"
  > omitZero(data.frame(logical=c(TRUE,TRUE,FALSE)))
  Error in UseMethod("omitZero") : 
    no applicable method for 'omitZero' applied to an object of class
"data.frame"
  > omitZero(c(one=1,zero=0,five=5))
   one five 
     1    5 
  > omitZero(matrix(0:3,2,2))
  [1] 1 2 3

In other situations the default case may work, perhaps slowly, for
all classes but I'll add special code for the simple classes so they
get dealt with more efficiently.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com