Re: [R] Replacing 0s with NA

From: Chuck Cleland <ccleland_at_optonline.net>
Date: Fri, 12 Jun 2009 05:54:17 -0400

On 6/12/2009 4:55 AM, 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.

X <- as.data.frame(matrix(sample(0:9, 100, replace=TRUE), ncol=10))

X

   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 7 5 8 9 6 6 4 8 5 8
2 6 2 9 6 8 5 9 1 1 3
3 4 1 5 8 9 5 3 2 1 4
4 4 8 7 7 4 1 1 4 9 8
5 9 2 5 8 4 8 4 8 6 0
6 3 4 2 8 2 0 6 4 8 5
7 3 5 0 2 7 7 9 9 3 1
8 7 3 3 4 8 3 9 2 7 1
9 4 7 9 1 5 4 8 2 1 9
10 7 7 6 1 0 9 0 5 7 0

X[] <- lapply(X, function(x){replace(x, x == 0, NA)})

X

   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 7 5 8 9 6 6 4 8 5 8
2 6 2 9 6 8 5 9 1 1 3
3 4 1 5 8 9 5 3 2 1 4
4 4 8 7 7 4 1 1 4 9 8
5 9 2 5 8 4 8 4 8 6 NA
6 3 4 2 8 2 NA 6 4 8 5
7 3 5 NA 2 7 7 9 9 3 1
8 7 3 3 4 8 3 9 2 7 1
9 4 7 9 1 5 4 8 2 1 9
10 7 7 6 1 NA 9 NA 5 7 NA

> 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.

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894

______________________________________________
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.
Received on Fri 12 Jun 2009 - 10:05:23 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 12 Jun 2009 - 10:32:48 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive