[R] Replace NaN with zero

Mike Prager mike.prager at noaa.gov
Tue Nov 25 21:30:21 CET 2008


"Spilak,Jacqueline [Edm]" <Jacqueline.Spilak at ec.gc.ca> wrote:

> I need help with replacing NaN with zero (the value '0') in my dataset.
> The reason is that I can't get it to graph because of the NaN in the
> dataset.  I have tried: 
> data[is.nan(data)] <- 0
> that others have suggested in the help archives but this does nothing so
> I am not sure what I am doing wrong.

The function is.nan() does not operate like is.na(). One could
consider that a design deficiency in R.

You can overcome it with apply(), is in this short script:

> tmp = data.frame(a = 1:3, b = 4:6)
> tmp$a[1] = 0/0
> print(tmp)
    a b
1 NaN 4
2   2 5
3   3 6
> mask <- apply(tmp, 2, is.nan)
> tmp2 <- tmp
> tmp2[mask] <-1000
> print(tmp2)
     a b
1 1000 4
2    2 5
3    3 6

Here I used 1000 instead of 0 to make it more easily seen. For
plotting, I would not use 0 as you propose, as that will plot a
point at zero. It is usually better to use NA, as in

> is.na(tmp2[mask]) <- TRUE

HTH


-- 
Mike Prager, NOAA, Beaufort, NC
* Opinions expressed are personal and not represented otherwise.
* Any use of tradenames does not constitute a NOAA endorsement.



More information about the R-help mailing list