[R] problem with NA and if
Bill.Venables at csiro.au
Bill.Venables at csiro.au
Fri Jul 4 09:00:30 CEST 2008
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.
More information about the R-help
mailing list