[R] Replacing 0s with NA
Gabor Grothendieck
ggrothendieck at gmail.com
Fri Jun 12 12:07:33 CEST 2009
Also try this:
X[X == 0] <- NA
or
X2 <- replace(X, X == 0, NA)
On Fri, Jun 12, 2009 at 5:54 AM, Chuck Cleland<ccleland at optonline.net> wrote:
> 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.
>
More information about the R-help
mailing list