Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum list of matrices with NAs

Tags:

r

matrix

I want to calculate the sum over matrices and ignore any NAs contained, as in the following example:

x1 <- matrix(c(NA,NA,2,2),2,2)
x2 <- matrix(c(NA,3,NA,NA),2,2)
x3 <- matrix(c(NA,NA,NA,NA),2,2)
x4 <- matrix(c(1,2,3,4),2,2)
lx <- list(x1,x2,x3,x4)
Reduce('+',lx) # does not work because of NAs

result <- matrix(c(1,5,5,6),2,2)

So the result should be:

      [,1] [,2]
[1,]    1    5
[2,]    5    6

How can this be done?

like image 270
user3032689 Avatar asked Oct 23 '25 15:10

user3032689


1 Answers

We can write a custom function and use it in Reduce. We replace the NAs with 0's and then we add them.

modifiedSum <- function(x, y) {
  replace(x, is.na(x), 0) + replace(y, is.na(y), 0)
}

Reduce(modifiedSum, lx)

#     [,1] [,2]
#[1,]    1    5
#[2,]    5    6
like image 65
Ronak Shah Avatar answered Oct 25 '25 06:10

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!