[R] replacing NA's with 0 in a dataframe for specified columns

John Fox jfox at mcmaster.ca
Wed Sep 15 21:16:25 CEST 2004


Dear Corey,

I'm afraid that this will entirely zero out any row with an NA in
column "a" or "c".

John

On Wed, 15 Sep 2004 13:05:14 -0600
 Corey Moffet <cmoffet at nwrc.ars.usda.gov> wrote:
> try:
> 
> x[is.na(x$a) | is.na(x$c),] <- 0
> 
> At 02:44 PM 9/15/2004 -0400, David Kane wrote:
> >I know that there must be a cool way of doing this, but I can't
> think
> >of it. Let's say I have an dataframe with NA's.
> >
> >> x <- data.frame(a = c(0,1,2,NA), b = c(0,NA,1,2), c = c(NA, 0, 1,
> 2))
> >> x
> >   a  b  c
> >1  0  0 NA
> >2  1 NA  0
> >3  2  1  1
> >4 NA  2  2
> >> 
> >
> >I know it is easy to replace all the NA's with zeroes.
> >
> >> x[is.na(x)] <- 0
> >> x
> >  a b c
> >1 0 0 0
> >2 1 0 0
> >3 2 1 1
> >4 0 2 2
> >> 
> >
> >But how do I do this for just columns a and c, leaving the NA in
> >column b alone?
> >
> >Thanks,
> >
> >Dave Kane
> >
> >> R.version
> >         _                
> >platform i686-pc-linux-gnu
> >arch     i686             
> >os       linux-gnu        
> >system   i686, linux-gnu  
> >status                    
> >major    1                
> >minor    9.1              
> >year     2004             
> >month    06               
> >day      21               
> >language R                
> >>
> >
> >______________________________________________
> >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
> >
> With best wishes and kind regards I am
> 
> Sincerely,
> 
> Corey A. Moffet
> Rangeland Scientist
> 
> ##################################################################
>                                             ####		     
> USDA-ARS                                        #		     
> Northwest Watershed Research Center             #		     
> 800 Park Blvd, Plaza IV, Suite 105          ###########   ####    
> Boise, ID 83712-7716                       #    #      # #        
> Voice: (208) 422-0718                      #    #  ####   ####    
> FAX:   (208) 334-1502                      #    # #           #   
>                                             ####   ###########    
> ##################################################################
> 
> ______________________________________________
> 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

--------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada
http://socserv.mcmaster.ca/jfox/




More information about the R-help mailing list