I have a list of matrix or matrix-like list. each matrix contains many NAs. Now I want to add all matrix up to a single matrix. (each matrix has the same dimension and dimnames)
a
V1 V2 V3
[1,] NA 4 21
[2,] NA NA 4
b
V1 V2 V3
[1,] NA NA 1
[2,] 5 0 12
# mylist = list(a,b)
after calculation, I want a result like
V1 V2 V3
[1,] NA 4 22
[2,] 5 0 16
SO I have two constraints:
constraint 1: keep (NA+NA)=NA
constraint 2: keep (NA+1) = 1
I have try the Reduce
and apply(simplify2array(.list), c(1,2), sum, na.rm=T)
functions as in the following page, but I cannot keep both constraints in the calculation.
Personally, using above example, I use the is.na
to identify all the NA
in each matrix, overlap logical values of each elements (a+b) , means if corresponding cells are all NAs, return length(mylist), say 2. then replace corresponding celss with NA
c = is.na(a) return
V1 V2 V3
[1,] 1 0 0
[2,] 1 1 0
d = is.na(b) return
V1 V2 V3
[1,] 1 1 0
[2,] 0 0 0
identify.na = c + d return
V1 V2 V3
[1,] 2 1 0
[2,] 1 1 0
result[identify.na==2] = NA
example is not the exactly code in R, just for example. Thanks in advance.