Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with NA in two lists?

Tags:

r

na

matrix

I have two lists and I want make them consistent in terms of NA. Put NA Whenever there is NA in one of the two lists without changing in anything else in the structure of the list.

set.seed(123)
m1 <- matrix(nrow=2,ncol=2,data=runif(4))
m1[1,1] <- NA
m2 <- matrix(nrow=2,ncol=2,data=runif(4))
m2[1,2] <- NA
lis <- list(m1, m2)
m1 <- matrix(nrow=2,ncol=2,data=runif(4))
m2 <- matrix(nrow=2,ncol=2,data=runif(4))
m2[2,1] <- NA
bis <- list(m1, m2)

I tried this but with no success bis[is.na(lis)]=NA

Desired output:

  > lis
[[1]]
          [,1]      [,2]
[1,]        NA 0.9568333
[2,] 0.4566147 0.4533342

[[2]]
         [,1]     [,2]
[1,] 0.9404673       NA
[2,] 0.0455565       NA

   > bis
 [[1]]
        [,1]      [,2]
[1,]        NA 0.9568333
[2,] 0.4566147 0.4533342

 [[2]]
         [,1]        [,2]
 [1,] 0.6775706        NA
 [2,] 0.5726334        NA
like image 994
bic ton Avatar asked Jan 21 '16 08:01

bic ton


1 Answers

Using Map to create a list of matrices with the NA positions as NA:

naposmtx <- Map(function(mtx1, mtx2){
    nasmtx <- mtx1 + mtx2 # because NA + non-NA = NA
    nasmtx[!is.na(nasmtx)] <- 0
    nasmtx
}, lis, bis)

Then:

lis <- Map(`+`, lis, naposmtx)
bis <- Map(`+`, bis, naposmtx)
like image 79
CJB Avatar answered Sep 29 '22 16:09

CJB