[R] Replacing 0s with NA

Gavin Simpson gavin.simpson at ucl.ac.uk
Fri Jun 12 12:02:36 CEST 2009


On Fri, 2009-06-12 at 09:55 +0100, Christine Griffiths wrote:
> Hello
> 
> I have a dataset in which I would like to replace 0s with NAs. There is a 
> lot of information on how to replace NAs with 0, but I have struggled to 
> find anything with regards to doing the reverse. Any recommendations would 
> be great.

Here is one way:

## some dummy data
set.seed(123)
dat <- matrix(rnorm(100), ncol = 10)
## add some 0's
dat[sample(100, 20)] <- 0
## convert to df
dat <- data.frame(dat)
dat

## now replace 0 with NA
## replacement function
foo <- function(x) {
    x[x == 0] <- NA
    x
}
## lapply it, and force back to df
dat2 <- data.frame(lapply(dat, foo))
dat2

HTH

G

> 
> Cheers
> Christine
> 
> ______________________________________________
> 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.
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%




More information about the R-help mailing list