Replace NA with 0 in R Data Frame

In this tutorial, we will learn how to replace all NA values in a data frame with zero number in R programming.

To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0.

The syntax to replace NA values with 0 in R data frame is

</>
Copy
 myDataframe[is.na(myDataframe)] = 0

where

  • myDataframe is the data frame in which you would like replace all NAs with 0.
  • is, na are keywords.

Example 1 – Replace NAs with 0 in R Data Frame

In this example, we will create an R data frame, DF1, with some of the values being NA.

</>
Copy
> DF1 = data.frame(C1= c(1, 5, 14, NA, 54), C2= c(9, NA, NA, 3, 42), C3= c(9, 7, 42, 87, NA))
> DF1
  C1 C2 C3
1  1  9  9
2  5 NA  7
3 14 NA 42
4 NA  3 87
5 54 42 NA
>

Now use the function is.na() with the data frame DF1.

</>
Copy
> DF1[is.na(DF1)] = 0
> DF1
  C1 C2 C3
1  1  9  9
2  5  0  7
3 14  0 42
4  0  3 87
5 54 42  0
>

Conclusion

In this R Tutorial, we have learnt how to replace all NA values in a data frame with zero number.