> -----Original Message-----
> From: r-help-boun...@r-project.org 
> [mailto:r-help-boun...@r-project.org] On Behalf Of Muhammad Rahiz
> Sent: Wednesday, March 24, 2010 9:21 AM
> To: tj
> Cc: r-help@r-project.org
> Subject: Re: [R] Summing with NA
> 
> Slightly longer method, but works as well.
> 
> z <- c(-12,-9)
> e <- c(-2,0)
> k <- c(NA,NA)
> 
> x <- c(z,e,k)
> x1 <- which(x!="NA",arr.ind=TRUE) # get elements which are not NA

Instead of x!="NA", which works here more or less by accident, use
   !is.na(x)

Your code "works" because x!="NA" is NA for any value of x
that is NA and which() considers NA to be the same as FALSE.
However, which(x!="String that a numeric will not be converted to")
will do the same.  Most functions do distinguish between NA
and FALSE in logical vectors so you will run into fewer surprises
if you use is.na(x) (rather than x!="NA") to see where the NA's in
x are.  (You will also save the time and memory involved in
converting x to a character vector.)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> x2 <- x[x1]
> 
> sum(x2)
> [1] -23
> 
> --
> Muhammad
> 
> 
> 
> 
> 
> tj wrote:
> > Hi all,
> > May I request for your help if you have time and if you 
> have an idea on how
> > to do this.  I want to add three vectors... And my goal is 
> to obtain the sum
> > of the vectors, ignoring the vector of "na"... 
> >
> > Here is what i did in R.. I'm adding the three vectors, 
> e,z,k, and my
> > objective is to get an answer = -23.
> > I tried putting the na.omit but it did not work.  Thanks.
> >
> >   
> >> z
> >>     
> > [1] -12  -9
> >   
> >> e
> >>     
> > [1] -2  0
> >   
> >> k
> >>     
> > [1] NA NA
> >   
> >> sum(z+e+k)
> >>     
> > [1] NA
> >   
> >
> >
> 
> ______________________________________________
> R-help@r-project.org 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.
> 

______________________________________________
R-help@r-project.org 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.

Reply via email to