How to replace 0 in list of matrices to NA in R?


Sometimes missing values are being read as 0 which is not a correct way to represent them, therefore, we must convert the 0’s in the data to NA so that R can understand the difference between missing value and 0’s. For this replacement, we can use lapply function and apply the replacement for all matrices using a function as shown in the below examples.

Example

 Live Demo

M1<-matrix(sample(c(0,rpois(6,5)),30,replace=TRUE),ncol=3)
M2<-matrix(sample(c(0,rpois(6,1)),30,replace=TRUE),ncol=3)
List1<-list(M1,M2)
List1

Output

[[1]]
   [,1] [,2] [,3]
[1,] 3    3    3
[2,] 3    0    5
[3,] 5    5    3
[4,] 3    3    5
[5,] 5    5    3
[6,] 3    3    3
[7,] 3    3    5
[8,] 5    3    3
[9,] 0    3    5
[10,] 5   3   3
[[2]]
   [,1] [,2] [,3]
[1,] 1    6    6
[2,] 1    6    1
[3,] 0    6    1
[4,] 0    1    6
[5,] 1    0    6
[6,] 6    0    6
[7,] 1    0    0
[8,] 0    6    0
[9,] 0    1    1
[10,] 0   1    1

lapply(List1,function(x) replace(x,x==0,NA))

[[1]]
    [,1] [,2] [,3]
[1,] 3   3    3
[2,] 3   NA    5
[3,] 5   5    3
[4,] 3   3    5
[5,] 5   5    3
[6,] 3   3    3
[7,] 3   3    5
[8,] 5   3    3
[9,] NA  3    5
[10,] 5  3   3
[[2]]
    [,1] [,2] [,3]
[1,] 1    6   6
[2,] 1    6    1
[3,] NA    6   1
[4,] NA    1   6
[5,] 1    NA   6
[6,] 6    NA   6
[7,] 1    NA   NA
[8,] NA   6   NA
[9,] NA   1   1
[10,] NA  1   1

Example

 Live Demo

M3<-matrix(sample(c(0,rpois(6,5)),20,replace=TRUE),ncol=4)
M4<-matrix(sample(c(0,rpois(6,1)),20,replace=TRUE),ncol=4)
List2<-list(M3,M4)
List2

Output

[[1]]
    [,1] [,2] [,3] [,4]
[1,] 5   4    4     3
[2,] 0   4    4     3
[3,] 4   6    6    0
[4,] 0   5    5    4
[5,] 6   5    0    0
[[2]]
   [,1] [,2] [,3] [,4]
[1,] 4   2   4     0
[2,] 0   0   2     0
[3,] 2   2   0    1
[4,] 4   4   1     0
[5,] 0   0   1     0

lapply(List2,function(x) replace(x,x==0,NA))

[[1]]
    [,1] [,2] [,3] [,4]
[1,] 5    4    4    3
[2,] NA   4    4    3
[3,] 4    6    6    NA
[4,] NA   5    5    4
[5,] 6    5    NA   NA
[[2]]
    [,1] [,2] [,3] [,4]
[1,] 4    2    4    NA
[2,] NA   NA   2    NA
[3,] 2   2     NA   1
[4,] 4    4   1    NA
[5,] NA  NA    1   NA

Updated on: 06-Feb-2021

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements