How to replace NAs with 0 in an R list that contains data.table objects?

R ProgrammingServer Side ProgrammingProgramming

To replace NAs with 0 in an R list that contains data.table objects, we can follow the below steps −

  • First of all, create a list of data.table objects that contain some NAs.

  • Then, use lapply function and is.na function to replace NAs with 0 in the list.

Example

Create the list

Let’s create a list as shown below −

library(data.table)
DT1<-
data.table(x1=sample(c(NA,rpois(5,5)),15,replace=TRUE),x2=sample(c(NA,rpois(5,1)),1
5,replace=TRUE))
DT2<
data.table(Y1=sample(c(NA,rpois(2,2)),15,replace=TRUE),Y2=sample(c(NA,rpois(2,5)),
15,replace=TRUE))
List<-list(DT1,DT2)
List

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

[[1]]
    x1 x2
1:  NA  0
2:   6  0
3:   7  0
4:  10  2
5:   7  0
6:  10  0
7:  NA  0
8:   7  2
9:  10 NA
10:  7  0
11:  6  0
12: 10 NA
13:  7  0
14:  7  2
15:  6 NA
[[2]]
    Y1 Y2
1:  NA NA
2:   4  4
3:   4  4
4:  NA  3
5:   4 NA
6:  NA NA
7:   4 NA
8:   1  4
9:   1  3
10:  1 NA
11: NA  4
12:  1  4
13:  1 NA
14: NA  3
15: NA NA

Replace NAs with 0

Using lapply function and is.na function to replace NAs with 0 in List as shown below −

library(data.table)
DT1<-
data.table(x1=sample(c(NA,rpois(5,5)),15,replace=TRUE),x2=sample(c(NA,rpois(5,1)),1
5,replace=TRUE))
DT2<-
data.table(Y1=sample(c(NA,rpois(2,2)),15,replace=TRUE),Y2=sample(c(NA,rpois(2,5)),
15,replace=TRUE))
List<-list(DT1,DT2)
lapply(List, function(x) {x[is.na(x)] <- 0; x})

Output

[[1]]
    x1 x2
1:   0 0
2:   6 0
3:   7 0
4:  10 2
5:   7 0
6:  10 0
7:   0 0
8:   7 2
9:  10 0
10:  7 0
11:  6 0
12: 10 0
13:  7 0
14:  7 2
15:  6 0
[[2]]
   Y1 Y2
1:  0 0
2:  4 4
3:  4 4
4:  0 3
5:  4 0
6:  0 0
7:  4 0
8:  1 4
9:  1 3
10: 1 0
11: 0 4
12: 1 4
13: 1 0
14: 0 3
15: 0 0
raja
Updated on 16-Nov-2021 05:39:54

Advertisements