Replace NA with 0 in a data frame column

Kunal Batra picture Kunal Batra · Nov 1, 2012 · Viewed 139.7k times · Source

Possible Duplicate:
Set NA to 0 in R

I have a data.frame with a column having NA values. I want to replace NA with 0 or any other value. I have tried a lot of threads and methods but it did not give me the result. I have tried the below methods.

a$x[a$x == NA] <- 0;
a[ , c("x")] <- apply(a[ , c("x")], 1, function(z){replace(z, is.na(z), 0)});
a$x[is.na(a$x), ] <- 0;

None of the above methods replaced NA with 0 in column x for data.frame a. Why?

Answer

themel picture themel · Nov 1, 2012

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0