[R] ignoring zeros or converting to NA
Bert Gunter
gunter.berton at gene.com
Thu Aug 14 23:33:40 CEST 2008
I don't want to belabor the point, but these are basically bad ideas. IEEE
floating point arithmetic is specifically designed to handle (at least the
usual) situations of division by exact 0, log(0), 0/0 and so forth with
special constants like Inf, -Inf and NaN (see ?Inf). Testing and converting
them to NA is both unnecessary and loses information (if calculations
require, test for the specific constants). +Inf, -Inf, NaN, and NA are
different and may mean entirely different things have happened in the course
of your calculations. R handles these situations gracefully -- as it does
NA's (at least R Base does).
Approximate zeros etc. are a different and much more difficult kettle of
fish. Thomas Lumley (and the R FAQ, I believe) has repeatedly mentioned the
classic "What Every Computer Scientist Should Know About Floating Point
Arithmetic" by David Goldberg to understand how difficult. The central
issue, of course, is HOW approximate does "approximate" need to be? Legions
of numerical analysts earn their pay working on this issue.
Cheers to all,
Bert Gunter
Genentech
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Daniel Malter
Sent: Thursday, August 14, 2008 1:46 PM
To: r-help at r-project.org
Subject: Re: [R] ignoring zeros or converting to NA
Sorry for jumping in. I haven't read the entire conversation. But imagine
you
want to compute 1/x for the entire matrix and your matrix has 0s and NAs.
Then you could do:
##define function
f<-function(x){1/x}
##sample data
y=c(0,1,2,3,4,5,6,7,NA)
##arrange in matrix
mat=matrix(y,3,3)
##apply function to matrix "mat"
##except 0s and NAs
calc.mat=ifelse(mat==0|is.na(mat)==T,NA,f(mat))
##inspect resulting matrix
calc.mat
If you are concerned about near zeros instead of zeros, you could adjust the
ifelse condition.
Best,
Daniel
rcoder wrote:
>
> Hi everyone,
>
> I have a matrix that has a combination of zeros and NAs. When I perform
> certain calculations on the matrix, the zeros generate "Inf" values. Is
> there a way to either convert the zeros in the matrix to NAs, or only
> perform the calculations if not zero (i.e. like using something similar to
> an !all(is.na() construct)?
>
> Thanks,
>
> rcoder
>
--
View this message in context:
http://www.nabble.com/ignoring-zeros-or-converting-to-NA-tp18948979p18989410
.html
Sent from the R help mailing list archive at Nabble.com.
______________________________________________
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