Was it helpful?

Question

How to replace NA values with zeros in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

We can replace all NA values by using is.na function

Example

> Data <- matrix(sample(c(NA, 0:9), 100, replace = TRUE), 10)
> df<-as.data.frame(Data)
> df
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 9 7 3 0 3 7 7 3 9 9
2 9 2 3 0 2 0 1 4 6 7
3 5 0 9 2 4 8 8 7 NA 5
4 7 3 1 2 6 NA 7 1 1 8
5 3 2 9 6 4 7 0 5 6 1
6 8 5 6 5 3 9 6 0 7 0
7 8 3 4 NA NA 0 2 4 2 NA
8 6 9 9 9 4 0 6 1 7 NA
9 5 5 NA 8 1 NA 0 9 9 3
10 1 1 0 7 1 1 4 1 2 1

Replacing NA’s by 0’s

> df[is.na(df)] <- 0
> df
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 9 7 3 0 3 7 7 3 9 9
2 9 2 3 0 2 0 1 4 6 7
3 5 0 9 2 4 8 8 7 0 5
4 7 3 1 2 6 0 7 1 1 8
5 3 2 9 6 4 7 0 5 6 1
6 8 5 6 5 3 9 6 0 7 0
7 8 3 4 0 0 0 2 4 2 0
8 6 9 9 9 4 0 6 1 7 0
9 5 5 0 8 1 0 0 9 9 3
10 1 1 0 7 1 1 4 1 2 1
raja
Published on 06-Jul-2020 16:10:21
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top