Re: [R] problem with NA and if

From: <Bill.Venables_at_csiro.au>
Date: Fri, 04 Jul 2008 17:00:30 +1000

This is an old one. NA is not a real value, but a marker of something missing. Hence the expression

a == NA

is really an incomplete expression (the right hand side of the equality is missing) and hence cannot be evaluated. Hence the error message. This is why the function is.na() exists, essentially.

There are a number of elegant solutions. Take an exampel

> x <- 1:5
> is.na(x[3]) <- TRUE ## the preferred way to set NA s
> x

[1] 1 2 NA 4 5
> sum(x, na.rm = TRUE)

[1] 12

alternatively:

> x[is.na(x)] <- 0
> x
[1] 1 2 0 4 5
> sum(x) ## probably what you were headed
[1] 12
>

Bill Venables
CSIRO Laboratories
PO Box 120, Cleveland, 4163
AUSTRALIA

Office Phone (email preferred): +61 7 3826 7251
Fax (if absolutely necessary):  +61 7 3826 7304
Mobile:                         +61 4 8819 4402
Home Phone:                     +61 7 3286 7700
mailto:Bill.Venables_at_csiro.au
http://www.cmis.csiro.au/bill.venables/

-----Original Message-----
From: r-help-bounces_at_r-project.org [mailto:r-help-bounces_at_r-project.org] On Behalf Of Keld Jørn Simonsen Sent: Friday, 4 July 2008 4:30 PM
To: r-help_at_r-project.org
Subject: [R] problem with NA and if

Hi

I would like to sum a number of time series, some of them having NA's

Standard action is here that if I sum a value with a NA, then the result is NA. I would like it to just keep the value.

I then try to:

 a = NA; if (a == NA) { a = 0}

just to try it out, but it says

Error in if (a == NA) { : missing value where TRUE/FALSE needed

What is wrong, and can I do it smarter? I looked at na.action but I don't see how it affects addition of vectors, nor time series.

Best regards
keld



R-help_at_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_at_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. Received on Fri 04 Jul 2008 - 07:04:41 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 04 Jul 2008 - 07:31:24 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.

list of date sections of archive