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

Berton Gunter gunter.berton at gene.com
Wed Sep 15 21:11:49 CEST 2004


But Spencer's solution would require looping to generalize to a large
numbers of columns.

In fact, you've given the answer already in your post:

xsub<-x[,somecols]
xsub[is.na(xsub)]<-0
x[,somecols]<-xsub

-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
 
"The business of the statistician is to catalyze the scientific learning
process."  - George E. P. Box
 
 

> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch 
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Spencer Graves
> Sent: Wednesday, September 15, 2004 12:01 PM
> To: David Kane
> Cc: r-help at stat.math.ethz.ch
> Subject: Re: [R] replacing NA's with 0 in a dataframe for 
> specified columns
> 
> Have you considered the following: 
> 
>  > x <- data.frame(a = c(0,1,2,NA), b = c(0,NA,1,2), c = 
> c(NA, 0, 1, 2))
>  > x$a[is.na(x$a)] <- 0
>  > x$c[is.na(x$c)] <- 0
>  > x
>   a  b c
> 1 0  0 0
> 2 1 NA 0
> 3 2  1 1
> 4 0  2 2
> 
>       hope this helps.  spencer graves
> 
> 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
> >  
> >
> 
> -- 
> Spencer Graves, PhD, Senior Development Engineer
> O:  (408)938-4420;  mobile:  (408)655-4567
> 
> ______________________________________________
> 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