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
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?see ?is.na Hence: if(!is.na(a[1])) b <- 7 Uwe Ligges> Thank you in advance! > Yours, > Mag. Ferri Leberl > > ______________________________________________ > R-help at 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.
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 LeberlNA 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