[R] Changing NA to 0 in selected columns of a dataframe

arun smartpink111 at yahoo.com
Fri Oct 12 00:58:44 CEST 2012


Hi,
Try this:
 dat1 = as.data.frame ( cbind ( A, B, C, D, E ) )
dat1$B[is.na(dat1$B)]<-0
 dat1$C[is.na(dat1$C)]<-0
 dat1
#  A B  C  D  E
#1 1 6  0 16 21
#2 2 7  0 17 NA
#3 3 0 13 18 NA
#4 4 0 14 19 NA
#5 5 0 15 20 25
A.K.




----- Original Message -----
From: scoyoc <scoyoc at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Thursday, October 11, 2012 6:05 PM
Subject: [R] Changing NA to 0 in selected columns of a dataframe

I've been beating my head on the table for hours now and don't understand why
this doesn't work. I have a dataframe that I want to change NAs to 0 for
some of the columns and not others. Consider this...

>#create dataframe
> A = c(1:5)
> B = c(6, 7, NA, NA, NA)
> C = c(NA, NA, 13, 14, 15)
> D = c(16:20)
> E = c(21, NA, NA, NA, 25)
> data = as.data.frame ( cbind ( A, B, C, D, E ) )
>#convert NAs in columns B & C to 0
> data [ is.na ( data [ , 2:3] ) ] = 0
Error in `[<-.data.frame`(`*tmp*`, is.na(data[, 2:3]), value = 0) : 
  only logical matrix subscripts are allowed in replacement

I only want to change NA in columns B and C. When I run this I get this
error. Why can't I designate rows using is.na()?



--
View this message in context: http://r.789695.n4.nabble.com/Changing-NA-to-0-in-selected-columns-of-a-dataframe-tp4645917.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
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