[R] ignoring zeros or converting to NA

Charles C. Berry cberry at tajo.ucsd.edu
Wed Aug 13 00:32:57 CEST 2008


On Tue, 12 Aug 2008, Mike Prager wrote:

> rcoder <mpdotbook at gmail.com> wrote:
>
>> 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)?
>
> Is this what you are looking for?
>
>> # make some data
>> a = matrix(c(rep(0,6), rep(2,6)), nrow = 4)
>> a
>     [,1] [,2] [,3]
> [1,]    0    0    2
> [2,]    0    0    2
> [3,]    0    2    2
> [4,]    0    2    2
>> # change zero to NA
>> is.na(a[a==0] ) <- TRUE

Or
 	is.na(a) <- a==0

Chuck

>> a
>     [,1] [,2] [,3]
> [1,]   NA   NA    2
> [2,]   NA   NA    2
> [3,]   NA    2    2
> [4,]   NA    2    2
>
> -- 
> Mike Prager, NOAA, Beaufort, NC
> * Opinions expressed are personal and not represented otherwise.
> * Any use of tradenames does not constitute a NOAA endorsement.
>
> ______________________________________________
> 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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list