Want to replace NA values with zeros in an R dataframe? Use the following simple example to replace NA values with zeros in an R dataframe.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | > m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10) > d <- as.data.frame(m) V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 1 4 3 NA 3 7 6 6 10 6 5 2 9 8 9 5 10 NA 2 1 7 2 3 1 1 6 3 6 NA 1 4 1 6 4 NA 4 NA 7 10 2 NA 4 1 8 5 1 2 4 NA 2 6 2 6 7 4 6 NA 3 NA NA 10 2 1 10 8 4 7 4 4 9 10 9 8 9 4 10 NA 8 5 8 3 2 1 4 5 9 4 7 9 3 9 10 1 9 9 10 5 3 3 10 4 2 2 5 NA 9 7 2 5 5 > d[is.na(d)] <- 0 > d V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 1 4 3 0 3 7 6 6 10 6 5 2 9 8 9 5 10 0 2 1 7 2 3 1 1 6 3 6 0 1 4 1 6 4 0 4 0 7 10 2 0 4 1 8 5 1 2 4 0 2 6 2 6 7 4 6 0 3 0 0 10 2 1 10 8 4 7 4 4 9 10 9 8 9 4 10 0 8 5 8 3 2 1 4 5 9 4 7 9 3 9 10 1 9 9 10 5 3 3 10 4 2 2 5 0 9 7 2 5 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.