[R] Changing zeros to NAs in a data frame

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Tue Nov 16 18:28:17 CET 2004



Laura Holt wrote:

> Dear R People:
> 
> I have a data frame with some columns that are numeric and some which 
> are factors.
> 
> There are zeros in the numeric columns and I would like to change them 
> to NAs.  However, there are zeros in some of the factor columns, and I 
> would like them to be left alone.
> 
> Is there a "global" way to do this, please?  I was thinking about use 
> the results from "str" but am not sure.
> 
> R Version 2.0.0 Windows.
> 

Let x be your data.frame. Then use:

is.num <- sapply(x, is.numeric)
x[is.num] <- lapply(x[is.num], function(y) ifelse(y == 0, NA, y))

HTH,

--sundar




More information about the R-help mailing list