Testing for missing values of numeric (double) vectors in R

July 13, 2007

(This article was first published on "R-bloggers" via Tal Galili in Google Reader, and kindly contributed to R-bloggers)

I just came across this bit of R trickiness when trying to improve the error messages for one of our packages. I tried adding a check at the C level for NA_REAL, but to no avail. The test failed even when I was certain that I was passing down a vector containing missing values. Consulting the Writing R Extensions Manual (WREM) led me quickly to ISNA. The WREM says that ISNA only applies to numeric values of type double and that other types can be checked by equality comparison to NA_INTEGER, NA_LOGICAL, etc. What could perhaps be better emphasized is that ISNA is the only appropriate way to test for missingness of REALSXP elements and that equality testing with NA_REAL does not work.

It is an easy mistake to make since one might be lulled into complacency by the repeating patterns of a switch statement. Here’s how NOT to do it:

SEXP hello_hasNA(SEXP v)
int i, found_na = 0;

for (i = 0; i < length(v); i++) {
switch (TYPEOF(v)) {
case INTSXP:
if (INTEGER(v)[i] == NA_INTEGER)
found_na = 1;
case LGLSXP:
if (LOGICAL(v)[i] == NA_LOGICAL)
found_na = 1;
if (REAL(v)[i] == NA_REAL) /* WRONG, must use ISNA() */
found_na = 1;
case STRSXP:
if (STRING_ELT(v, i) == NA_STRING)
found_na = 1;
error(“no support for type”);
if (found_na)
return ScalarLogical(found_na);

To fix things, replace the REALSXP case like this:

if (ISNA(REAL(v)[i]))
found_na = 1;

Technorati Tags: programming, R

To leave a comment for the author, please follow the link and comment on their blog: "R-bloggers" via Tal Galili in Google Reader.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...


Comments are closed.


Mango solutions

plotly webpage

dominolab webpage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training





CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)