Replace NA with 0 in R (Example)
This tutorial shows how to replace NA values with zero in the R programming language.
Example Data
vec <- c(2, NA, 5, NA, 8, 3) # Create example vector vec # Print example vector # 2 NA 5 NA 8 3 |
vec <- c(2, NA, 5, NA, 8, 3) # Create example vector vec # Print example vector # 2 NA 5 NA 8 3
Replace NA with Zero in R
vec[is.na(vec)] <- 0 # Replace NA with 0 vec # Print updated vector # 2 0 5 0 8 3 |
vec[is.na(vec)] <- 0 # Replace NA with 0 vec # Print updated vector # 2 0 5 0 8 3
In the previous example, we changed NAs of a vector to 0. However, we can apply the same operation to a data frame column.
Video Example
The following video shows more examples for the replacement of missing data by zero in R.
2 Comments. Leave new
thanks! it was super easy to understabd
Thanks Rushali, that’s nice to hear!