[R] Changing zeros to NAs in a data frame

Andy Bunn abunn at whrc.org
Tue Nov 16 18:30:38 CET 2004


This isn't pretty but it's a way to do it:

foo <- data.frame(x = c(1,0,1,1,0,2,4), y = as.factor(c(0,2,1,1,0,3,1)))
Zero2NA <- function(x){
    if(is.numeric(x)) { x[x == 0] <- NA; }
    return(x)
}
foo2 <- as.data.frame(lapply(foo, Zero2NA))
foo
foo2

HTH, Andy


> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch]On Behalf Of Laura Holt
> Sent: Tuesday, November 16, 2004 11:31 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Changing zeros to NAs in a data frame
>
>
> 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.
>
> Thanks in advance.
> Sincerely,
> Laura Holt
> mailto: lauraholt_983 at hotmail.com
>
>
> Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list