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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With