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

scoyoc scoyoc at gmail.com
Fri Oct 12 00:05:41 CEST 2012


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.



More information about the R-help mailing list