[R] inequality with NA

Marc Schwartz (via MN) mschwartz at mn.rr.com
Fri Sep 22 20:32:57 CEST 2006


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?
> Thank you in advance!
> 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



More information about the R-help mailing list