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

Rui Barradas ruipbarradas at sapo.pt
Fri Oct 12 00:52:54 CEST 2012


Hello,

Try the following.

data[ , 2:3][is.na(data[ , 2:3] ) ] = 0

You have to tell the interpreter which columns you want to change.

Hope this helps,

Rui Barradas
Em 11-10-2012 23:05, scoyoc escreveu:
> 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