[R] NA and logical indexes

Berwin A Turlach berwin at maths.uwa.edu.au
Sat Nov 29 06:37:37 CET 2008


G'day Sebastian,

On Fri, 28 Nov 2008 16:35:13 -0600
"Sebastian P. Luque" <spluque at gmail.com> wrote:

> On Fri, 28 Nov 2008 22:01:15 -0000 (GMT),
> (Ted Harding) <Ted.Harding at manchester.ac.uk> wrote:
>
> > NA can seem to have a bewildering logic, but it all becomes clear if
> > you interpret NA as "value unkown".
> > [...] 
> > Clear? ( :)) Hoping this helps, Ted.
> 
> Crystal!  It's something that one needs to be extra careful with when
> playing with logicals.

Or, rather, if you expect that your code one day has to handle data in
which values from which you construct logicals might be missing (NA),
then it might be worthwhile to think carefully about this case and how
you want to handle missing values.  In your case, do you want to
return the rows where foo$A is missing or not?  Both is possible:

R> foo <- data.frame(A=gl(2, 5, labels=letters[1:2]), X=runif(10))
R> foo$A[1] <- NA
R> foo[!is.na(foo$A) & foo$A == "b", ]  
   A         X
6  b 0.8418619
7  b 0.6833322
8  b 0.1582648
9  b 0.4431542
10 b 0.7603365
R> foo[is.na(foo$A) | foo$A == "b", ]  
      A         X
1  <NA> 0.8922147
6     b 0.8418619
7     b 0.6833322
8     b 0.1582648
9     b 0.4431542
10    b 0.7603365

Cheers,

	Berwin

=========================== Full address =============================
Berwin A Turlach                            Tel.: +65 6516 4416 (secr)
Dept of Statistics and Applied Probability        +65 6516 6650 (self)
Faculty of Science                          FAX : +65 6872 3919       
National University of Singapore     
6 Science Drive 2, Blk S16, Level 7          e-mail: statba at nus.edu.sg
Singapore 117546                    http://www.stat.nus.edu.sg/~statba



More information about the R-help mailing list