# Re: [R] inequality with NA

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Fri 22 Sep 2006 - 18:32:57 GMT

On Fri, 2006-09-22 at 20:16 +0200, Mag. Ferri Leberl wrote:
> Dear everybody!
> take a<-c(5,3,NA,6).
>
> if(a[1]!=NA){b<-7}
> if(a[3]!=5){b<-7}
> if(a[3]!=NA){b<-7}
> if(a[3]==NA){b<-7}
>
> will alltogeather return
>
> Fehler in if (a[1] != NA) { : Fehlender Wert, wo TRUE/FALSE nötig ist
>
> (or simularly). Somehow this is logical. But how else should I get out,
> whether a certain vector-component has an existing value?
> Yours,
> Mag. Ferri Leberl

NA is not defined, so you cannot predictably perform equality/inequality tests with it. There are specific functions in place for dealing with this.

See ?is.na and ?na.omit

> a

[1] 5 3 NA 6

> a[is.na(a)]

[1] NA

> a[!is.na(a)]

[1] 5 3 6

You can also use which() to find the indices:

> which(is.na(a))

[1] 3

> which(!is.na(a))

[1] 1 2 4

Finally, use na.omit() to remove all NA's:

> na.omit(a)

[1] 5 3 6
attr(,"na.action")
[1] 3
attr(,"class")
[1] "omit"

Note that the object attribute 'na.action' shows that a[3] was removed:

> a.omit <- na.omit(a)

> as.vector(attr(a.omit, "na.action"))

[1] 3

HTH, Marc Schwartz

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sat Sep 23 04:35:51 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 22 Sep 2006 - 19:30:06 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.