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?
Since nobody so far felt fit to point out why what you’re trying doesn’t work:
NA == NAdoesn’t returnTRUE, it returnsNA(since comparing to undefined values should yield an undefined result).applyon an atomic vector. You can’t useapplyto loop over the elements in a column.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