Hi, is there a hasNA() / an anyNA() function in R? Of course, hasNA <- function(x) { any(is.na(x)); } would do, but that would scan all elements in 'x' and then do the test. I'm looking for a more efficient implementation that returns TRUE at the first NA, e.g. hasNA <- function(x) { for (kk in seq(along=x)) { if (is.na(x[kk])) return(TRUE); } FALSE; } Cheers Henrik
I don't know of one. Ideally, instead of a specifc function anyNA() function, any() could be perhaps be extended to any(x, FUN) where FUN returns a logical for an element of x, and implemented to find the 1st instance as you suggest. Mike On 8/13/07, Henrik Bengtsson <hb@stat.berkeley.edu> wrote:> > Hi, > > is there a hasNA() / an anyNA() function in R? Of course, > > hasNA <- function(x) { > any(is.na(x)); > } > > would do, but that would scan all elements in 'x' and then do the > test. I'm looking for a more efficient implementation that returns > TRUE at the first NA, e.g. > > hasNA <- function(x) { > for (kk in seq(along=x)) { > if (is.na(x[kk])) > return(TRUE); > } > FALSE; > } > > Cheers > > Henrik > > ______________________________________________ > R-devel@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-devel >[[alternative HTML version deleted]]
Why not hasNA <- function(x) !is.na(match(NA, x)) -Ben
S-PLUS has an anyMissing() function, for which the default is: anyMissing.default <- function(x){ (length(which.na(x)) > 0) } This is more efficient than any(is.na(x)) in the usual case that there are few or no missing values. There are methods for vectors that drop to C code, and methods for data frames and other classes. The code below seems to presume a list, and would be very slow for vectors. For reasons of consistency between S-PLUS and R, I would ask that an R function be called anyMissing rather than hasNA or anyNA. Tim Hesterberg>is there a hasNA() / an anyNA() function in R? Of course, > >hasNA <- function(x) { > any(is.na(x)); >} > >would do, but that would scan all elements in 'x' and then do the >test. I'm looking for a more efficient implementation that returns >TRUE at the first NA, e.g. > >hasNA <- function(x) { > for (kk in seq(along=x)) { > if (is.na(x[kk])) > return(TRUE); > } > FALSE; >} > >Cheers > >Henrik
Reasonably Related Threads
- anyNA() performance on vectors of POSIXct
- Internal state indicating if a data object has NAs/no NAs/not sure (Was: Re: Speeding up matrix multiplies)
- could not find function "anyNA" when building tools package in R 3.1.1
- anyNA() performance on vectors of POSIXct
- Memory leakage/violation?